-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathUnwrappedLineFormatter.cpp
1597 lines (1442 loc) · 61.1 KB
/
UnwrappedLineFormatter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "UnwrappedLineFormatter.h"
#include "FormatToken.h"
#include "NamespaceEndCommentsFixer.h"
#include "WhitespaceManager.h"
#include "llvm/Support/Debug.h"
#include <queue>
#define DEBUG_TYPE "format-formatter"
namespace clang {
namespace format {
namespace {
bool startsExternCBlock(const AnnotatedLine &Line) {
const FormatToken *Next = Line.First->getNextNonComment();
const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
NextNext && NextNext->is(tok::l_brace);
}
bool isRecordLBrace(const FormatToken &Tok) {
return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
TT_StructLBrace, TT_UnionLBrace);
}
/// Tracks the indent level of \c AnnotatedLines across levels.
///
/// \c nextLine must be called for each \c AnnotatedLine, after which \c
/// getIndent() will return the indent for the last line \c nextLine was called
/// with.
/// If the line is not formatted (and thus the indent does not change), calling
/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
/// subsequent lines on the same level to be indented at the same level as the
/// given line.
class LevelIndentTracker {
public:
LevelIndentTracker(const FormatStyle &Style,
const AdditionalKeywords &Keywords, unsigned StartLevel,
int AdditionalIndent)
: Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
for (unsigned i = 0; i != StartLevel; ++i)
IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
}
/// Returns the indent for the current line.
unsigned getIndent() const { return Indent; }
/// Update the indent state given that \p Line is going to be formatted
/// next.
void nextLine(const AnnotatedLine &Line) {
Offset = getIndentOffset(*Line.First);
// Update the indent level cache size so that we can rely on it
// having the right size in adjustToUnmodifiedline.
if (Line.Level >= IndentForLevel.size())
IndentForLevel.resize(Line.Level + 1, -1);
if (Style.IndentPPDirectives != FormatStyle::PPDIS_None &&
(Line.InPPDirective ||
(Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
Line.Type == LT_CommentAbovePPDirective))) {
unsigned PPIndentWidth =
(Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
Indent = Line.InMacroBody
? Line.PPLevel * PPIndentWidth +
(Line.Level - Line.PPLevel) * Style.IndentWidth
: Line.Level * PPIndentWidth;
Indent += AdditionalIndent;
} else {
// When going to lower levels, forget previous higher levels so that we
// recompute future higher levels. But don't forget them if we enter a PP
// directive, since these do not terminate a C++ code block.
if (!Line.InPPDirective) {
assert(Line.Level <= IndentForLevel.size());
IndentForLevel.resize(Line.Level + 1);
}
Indent = getIndent(Line.Level);
}
if (static_cast<int>(Indent) + Offset >= 0)
Indent += Offset;
if (Line.IsContinuation)
Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
}
/// Update the level indent to adapt to the given \p Line.
///
/// When a line is not formatted, we move the subsequent lines on the same
/// level to the same indent.
/// Note that \c nextLine must have been called before this method.
void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
if (Line.InPPDirective)
return;
assert(Line.Level < IndentForLevel.size());
if (Line.First->is(tok::comment) && IndentForLevel[Line.Level] != -1)
return;
unsigned LevelIndent = Line.First->OriginalColumn;
if (static_cast<int>(LevelIndent) - Offset >= 0)
LevelIndent -= Offset;
IndentForLevel[Line.Level] = LevelIndent;
}
private:
/// Get the offset of the line relatively to the level.
///
/// For example, 'public:' labels in classes are offset by 1 or 2
/// characters to the left from their level.
int getIndentOffset(const FormatToken &RootToken) {
if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
Style.isCSharp()) {
return 0;
}
auto IsAccessModifier = [this, &RootToken]() {
if (RootToken.isAccessSpecifier(Style.isCpp())) {
return true;
} else if (RootToken.isObjCAccessSpecifier()) {
return true;
}
// Handle Qt signals.
else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
RootToken.Next && RootToken.Next->is(tok::colon)) {
return true;
} else if (RootToken.Next &&
RootToken.Next->isOneOf(Keywords.kw_slots,
Keywords.kw_qslots) &&
RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) {
return true;
}
// Handle malformed access specifier e.g. 'private' without trailing ':'.
else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
return true;
}
return false;
};
if (IsAccessModifier()) {
// The AccessModifierOffset may be overridden by IndentAccessModifiers,
// in which case we take a negative value of the IndentWidth to simulate
// the upper indent level.
return Style.IndentAccessModifiers ? -Style.IndentWidth
: Style.AccessModifierOffset;
}
return 0;
}
/// Get the indent of \p Level from \p IndentForLevel.
///
/// \p IndentForLevel must contain the indent for the level \c l
/// at \p IndentForLevel[l], or a value < 0 if the indent for
/// that level is unknown.
unsigned getIndent(unsigned Level) const {
assert(Level < IndentForLevel.size());
if (IndentForLevel[Level] != -1)
return IndentForLevel[Level];
if (Level == 0)
return 0;
return getIndent(Level - 1) + Style.IndentWidth;
}
const FormatStyle &Style;
const AdditionalKeywords &Keywords;
const unsigned AdditionalIndent;
/// The indent in characters for each level. It remembers the indent of
/// previous lines (that are not PP directives) of equal or lower levels. This
/// is used to align formatted lines to the indent of previous non-formatted
/// lines. Think about the --lines parameter of clang-format.
SmallVector<int> IndentForLevel;
/// Offset of the current line relative to the indent level.
///
/// For example, the 'public' keywords is often indented with a negative
/// offset.
int Offset = 0;
/// The current line's indent.
unsigned Indent = 0;
};
const FormatToken *getMatchingNamespaceToken(
const AnnotatedLine *Line,
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
if (!Line->startsWith(tok::r_brace))
return nullptr;
size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
if (StartLineIndex == UnwrappedLine::kInvalidIndex)
return nullptr;
assert(StartLineIndex < AnnotatedLines.size());
return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
}
StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
return NamespaceToken ? NamespaceToken->TokenText : StringRef();
}
StringRef getMatchingNamespaceTokenText(
const AnnotatedLine *Line,
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
const FormatToken *NamespaceToken =
getMatchingNamespaceToken(Line, AnnotatedLines);
return NamespaceToken ? NamespaceToken->TokenText : StringRef();
}
class LineJoiner {
public:
LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
const SmallVectorImpl<AnnotatedLine *> &Lines)
: Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
AnnotatedLines(Lines) {}
/// Returns the next line, merging multiple lines into one if possible.
const AnnotatedLine *getNextMergedLine(bool DryRun,
LevelIndentTracker &IndentTracker) {
if (Next == End)
return nullptr;
const AnnotatedLine *Current = *Next;
IndentTracker.nextLine(*Current);
unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
if (MergedLines > 0 && Style.ColumnLimit == 0) {
// Disallow line merging if there is a break at the start of one of the
// input lines.
for (unsigned i = 0; i < MergedLines; ++i)
if (Next[i + 1]->First->NewlinesBefore > 0)
MergedLines = 0;
}
if (!DryRun)
for (unsigned i = 0; i < MergedLines; ++i)
join(*Next[0], *Next[i + 1]);
Next = Next + MergedLines + 1;
return Current;
}
private:
/// Calculates how many lines can be merged into 1 starting at \p I.
unsigned
tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
const unsigned Indent = IndentTracker.getIndent();
// Can't join the last line with anything.
if (I + 1 == E)
return 0;
// We can never merge stuff if there are trailing line comments.
const AnnotatedLine *TheLine = *I;
if (TheLine->Last->is(TT_LineComment))
return 0;
const auto &NextLine = *I[1];
if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore)
return 0;
if (TheLine->InPPDirective &&
(!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
return 0;
}
if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
return 0;
unsigned Limit =
Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
// If we already exceed the column limit, we set 'Limit' to 0. The different
// tryMerge..() functions can then decide whether to still do merging.
Limit = TheLine->Last->TotalLength > Limit
? 0
: Limit - TheLine->Last->TotalLength;
if (TheLine->Last->is(TT_FunctionLBrace) &&
TheLine->First == TheLine->Last &&
!Style.BraceWrapping.SplitEmptyFunction &&
NextLine.First->is(tok::r_brace)) {
return tryMergeSimpleBlock(I, E, Limit);
}
const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr;
// Handle empty record blocks where the brace has already been wrapped.
if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
TheLine->First == TheLine->Last) {
bool EmptyBlock = NextLine.First->is(tok::r_brace);
const FormatToken *Tok = PreviousLine->First;
if (Tok && Tok->is(tok::comment))
Tok = Tok->getNextNonComment();
if (Tok && Tok->getNamespaceToken()) {
return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (Tok && Tok->is(tok::kw_typedef))
Tok = Tok->getNextNonComment();
if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
tok::kw_extern, Keywords.kw_interface)) {
return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (Tok && Tok->is(tok::kw_template) &&
Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
return 0;
}
}
auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine,
TheLine]() {
if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All)
return true;
if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
NextLine.First->is(tok::r_brace)) {
return true;
}
if (Style.AllowShortFunctionsOnASingleLine &
FormatStyle::SFS_InlineOnly) {
// Just checking TheLine->Level != 0 is not enough, because it
// provokes treating functions inside indented namespaces as short.
if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
return true;
if (TheLine->Level != 0) {
if (!PreviousLine)
return false;
// TODO: Use IndentTracker to avoid loop?
// Find the last line with lower level.
const AnnotatedLine *Line = nullptr;
for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
assert(*J);
if (!(*J)->InPPDirective && !(*J)->isComment() &&
(*J)->Level < TheLine->Level) {
Line = *J;
break;
}
}
if (!Line)
return false;
// Check if the found line starts a record.
const auto *LastNonComment = Line->getLastNonComment();
// There must be another token (usually `{`), because we chose a
// non-PPDirective and non-comment line that has a smaller level.
assert(LastNonComment);
return isRecordLBrace(*LastNonComment);
}
}
return false;
};
bool MergeShortFunctions = ShouldMergeShortFunctions();
const auto *FirstNonComment = TheLine->getFirstNonComment();
if (!FirstNonComment)
return 0;
// FIXME: There are probably cases where we should use FirstNonComment
// instead of TheLine->First.
if (Style.CompactNamespaces) {
if (const auto *NSToken = TheLine->First->getNamespaceToken()) {
int J = 1;
assert(TheLine->MatchingClosingBlockLineIndex > 0);
for (auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
I + J != E && NSToken->TokenText == getNamespaceTokenText(I[J]) &&
ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
I[J]->Last->TotalLength < Limit;
++J, --ClosingLineIndex) {
Limit -= I[J]->Last->TotalLength;
// Reduce indent level for bodies of namespaces which were compacted,
// but only if their content was indented in the first place.
auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
const int OutdentBy = I[J]->Level - TheLine->Level;
assert(OutdentBy >= 0);
for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
++CompactedLine) {
if (!(*CompactedLine)->InPPDirective) {
const int Level = (*CompactedLine)->Level;
(*CompactedLine)->Level = std::max(Level - OutdentBy, 0);
}
}
}
return J - 1;
}
if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
int i = 0;
unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
for (; I + 1 + i != E &&
nsToken->TokenText ==
getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
i++, --openingLine) {
// No space between consecutive braces.
I[i + 1]->First->SpacesRequiredBefore =
I[i]->Last->isNot(tok::r_brace);
// Indent like the outer-most namespace.
IndentTracker.nextLine(*I[i + 1]);
}
return i;
}
}
const auto *LastNonComment = TheLine->getLastNonComment();
assert(LastNonComment);
// FIXME: There are probably cases where we should use LastNonComment
// instead of TheLine->Last.
// Try to merge a function block with left brace unwrapped.
if (LastNonComment->is(TT_FunctionLBrace) &&
TheLine->First != LastNonComment) {
return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
}
// Try to merge a control statement block with left brace unwrapped.
if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
TT_ForEachMacro)) {
return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
// Try to merge a control statement block with left brace wrapped.
if (NextLine.First->is(tok::l_brace)) {
if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
tok::kw_for, tok::kw_switch, tok::kw_try,
tok::kw_do, TT_ForEachMacro) ||
(TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_MultiLine) {
// If possible, merge the next line's wrapped left brace with the
// current line. Otherwise, leave it on the next line, as this is a
// multi-line control statement.
return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
TheLine->Last->TotalLength <=
Style.ColumnLimit)
? 1
: 0;
}
if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
tok::kw_for, TT_ForEachMacro)) {
return (Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always)
? tryMergeSimpleBlock(I, E, Limit)
: 0;
}
if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_MultiLine) {
// This case if different from the upper BWACS_MultiLine processing
// in that a preceding r_brace is not on the same line as else/catch
// most likely because of BeforeElse/BeforeCatch set to true.
// If the line length doesn't fit ColumnLimit, leave l_brace on the
// next line to respect the BWACS_MultiLine.
return (Style.ColumnLimit == 0 ||
TheLine->Last->TotalLength <= Style.ColumnLimit)
? 1
: 0;
}
}
if (PreviousLine && TheLine->First->is(tok::l_brace)) {
switch (PreviousLine->First->Tok.getKind()) {
case tok::at:
// Don't merge block with left brace wrapped after ObjC special blocks.
if (PreviousLine->First->Next) {
tok::ObjCKeywordKind kwId =
PreviousLine->First->Next->Tok.getObjCKeywordID();
if (kwId == tok::objc_autoreleasepool ||
kwId == tok::objc_synchronized) {
return 0;
}
}
break;
case tok::kw_case:
case tok::kw_default:
// Don't merge block with left brace wrapped after case labels.
return 0;
default:
break;
}
}
// Don't merge an empty template class or struct if SplitEmptyRecords
// is defined.
if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
const FormatToken *Previous = PreviousLine->Last;
if (Previous) {
if (Previous->is(tok::comment))
Previous = Previous->getPreviousNonComment();
if (Previous) {
if (Previous->is(tok::greater) && !PreviousLine->InPPDirective)
return 0;
if (Previous->is(tok::identifier)) {
const FormatToken *PreviousPrevious =
Previous->getPreviousNonComment();
if (PreviousPrevious &&
PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
return 0;
}
}
}
}
}
if (TheLine->Last->is(tok::l_brace)) {
bool ShouldMerge = false;
// Try to merge records.
if (TheLine->Last->is(TT_EnumLBrace)) {
ShouldMerge = Style.AllowShortEnumsOnASingleLine;
} else if (TheLine->Last->is(TT_RequiresExpressionLBrace)) {
ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine;
} else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
// NOTE: We use AfterClass (whereas AfterStruct exists) for both classes
// and structs, but it seems that wrapping is still handled correctly
// elsewhere.
ShouldMerge = !Style.BraceWrapping.AfterClass ||
(NextLine.First->is(tok::r_brace) &&
!Style.BraceWrapping.SplitEmptyRecord);
} else if (TheLine->InPPDirective ||
!TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
tok::kw_struct)) {
// Try to merge a block with left brace unwrapped that wasn't yet
// covered.
ShouldMerge = !Style.BraceWrapping.AfterFunction ||
(NextLine.First->is(tok::r_brace) &&
!Style.BraceWrapping.SplitEmptyFunction);
}
return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
}
// Try to merge a function block with left brace wrapped.
if (NextLine.First->is(TT_FunctionLBrace) &&
Style.BraceWrapping.AfterFunction) {
if (NextLine.Last->is(TT_LineComment))
return 0;
// Check for Limit <= 2 to account for the " {".
if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
return 0;
Limit -= 2;
unsigned MergedLines = 0;
if (MergeShortFunctions ||
(Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
NextLine.First == NextLine.Last && I + 2 != E &&
I[2]->First->is(tok::r_brace))) {
MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
// If we managed to merge the block, count the function header, which is
// on a separate line.
if (MergedLines > 0)
++MergedLines;
}
return MergedLines;
}
auto IsElseLine = [&TheLine]() -> bool {
const FormatToken *First = TheLine->First;
if (First->is(tok::kw_else))
return true;
return First->is(tok::r_brace) && First->Next &&
First->Next->is(tok::kw_else);
};
if (TheLine->First->is(tok::kw_if) ||
(IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
FormatStyle::SIS_AllIfsAndElse))) {
return Style.AllowShortIfStatementsOnASingleLine
? tryMergeSimpleControlStatement(I, E, Limit)
: 0;
}
if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
TT_ForEachMacro)) {
return Style.AllowShortLoopsOnASingleLine
? tryMergeSimpleControlStatement(I, E, Limit)
: 0;
}
if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
return Style.AllowShortCaseLabelsOnASingleLine
? tryMergeShortCaseLabels(I, E, Limit)
: 0;
}
if (TheLine->InPPDirective &&
(TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
return tryMergeSimplePPDirective(I, E, Limit);
}
return 0;
}
unsigned
tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (Limit == 0)
return 0;
if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
return 0;
if (1 + I[1]->Last->TotalLength > Limit)
return 0;
return 1;
}
unsigned tryMergeSimpleControlStatement(
SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
if (Limit == 0)
return 0;
if (Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always &&
I[1]->First->is(tok::l_brace) &&
Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
return 0;
}
if (I[1]->InPPDirective != (*I)->InPPDirective ||
(I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
return 0;
}
Limit = limitConsideringMacros(I + 1, E, Limit);
AnnotatedLine &Line = **I;
if (Line.First->isNot(tok::kw_do) && Line.First->isNot(tok::kw_else) &&
Line.Last->isNot(tok::kw_else) && Line.Last->isNot(tok::r_paren)) {
return 0;
}
// Only merge `do while` if `do` is the only statement on the line.
if (Line.First->is(tok::kw_do) && Line.Last->isNot(tok::kw_do))
return 0;
if (1 + I[1]->Last->TotalLength > Limit)
return 0;
// Don't merge with loops, ifs, a single semicolon or a line comment.
if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
TT_ForEachMacro, TT_LineComment)) {
return 0;
}
// Only inline simple if's (no nested if or else), unless specified
if (Style.AllowShortIfStatementsOnASingleLine ==
FormatStyle::SIS_WithoutElse) {
if (I + 2 != E && Line.startsWith(tok::kw_if) &&
I[2]->First->is(tok::kw_else)) {
return 0;
}
}
return 1;
}
unsigned
tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (Limit == 0 || I + 1 == E ||
I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
return 0;
}
if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
return 0;
unsigned NumStmts = 0;
unsigned Length = 0;
bool EndsWithComment = false;
bool InPPDirective = I[0]->InPPDirective;
bool InMacroBody = I[0]->InMacroBody;
const unsigned Level = I[0]->Level;
for (; NumStmts < 3; ++NumStmts) {
if (I + 1 + NumStmts == E)
break;
const AnnotatedLine *Line = I[1 + NumStmts];
if (Line->InPPDirective != InPPDirective)
break;
if (Line->InMacroBody != InMacroBody)
break;
if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
break;
if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
tok::kw_while) ||
EndsWithComment) {
return 0;
}
if (Line->First->is(tok::comment)) {
if (Level != Line->Level)
return 0;
SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
for (; J != E; ++J) {
Line = *J;
if (Line->InPPDirective != InPPDirective)
break;
if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
break;
if (Line->First->isNot(tok::comment) || Level != Line->Level)
return 0;
}
break;
}
if (Line->Last->is(tok::comment))
EndsWithComment = true;
Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
}
if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
return 0;
return NumStmts;
}
unsigned
tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
// Don't merge with a preprocessor directive.
if (I[1]->Type == LT_PreprocessorDirective)
return 0;
AnnotatedLine &Line = **I;
// Don't merge ObjC @ keywords and methods.
// FIXME: If an option to allow short exception handling clauses on a single
// line is added, change this to not return for @try and friends.
if (Style.Language != FormatStyle::LK_Java &&
Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
return 0;
}
// Check that the current line allows merging. This depends on whether we
// are in a control flow statements as well as several style flags.
if (Line.First->is(tok::kw_case) ||
(Line.First->Next && Line.First->Next->is(tok::kw_else))) {
return 0;
}
// default: in switch statement
if (Line.First->is(tok::kw_default)) {
const FormatToken *Tok = Line.First->getNextNonComment();
if (Tok && Tok->is(tok::colon))
return 0;
}
auto IsCtrlStmt = [](const auto &Line) {
return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
tok::kw_do, tok::kw_for, TT_ForEachMacro);
};
const bool IsSplitBlock =
Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
(Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
I[1]->First->isNot(tok::r_brace));
if (IsCtrlStmt(Line) ||
Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
tok::kw___finally, tok::r_brace,
Keywords.kw___except)) {
if (IsSplitBlock)
return 0;
// Don't merge when we can't except the case when
// the control statement block is empty
if (!Style.AllowShortIfStatementsOnASingleLine &&
Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
!Style.BraceWrapping.AfterControlStatement &&
I[1]->First->isNot(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortIfStatementsOnASingleLine &&
Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always &&
I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortLoopsOnASingleLine &&
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
TT_ForEachMacro) &&
!Style.BraceWrapping.AfterControlStatement &&
I[1]->First->isNot(tok::r_brace)) {
return 0;
}
if (!Style.AllowShortLoopsOnASingleLine &&
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
TT_ForEachMacro) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_Always &&
I + 2 != E && I[2]->First->isNot(tok::r_brace)) {
return 0;
}
// FIXME: Consider an option to allow short exception handling clauses on
// a single line.
// FIXME: This isn't covered by tests.
// FIXME: For catch, __except, __finally the first token on the line
// is '}', so this isn't correct here.
if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
Keywords.kw___except, tok::kw___finally)) {
return 0;
}
}
if (const auto *LastNonComment = Line.getLastNonComment();
LastNonComment && LastNonComment->is(tok::l_brace)) {
if (IsSplitBlock && Line.First == Line.Last &&
I > AnnotatedLines.begin() &&
(I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
return 0;
}
FormatToken *Tok = I[1]->First;
auto ShouldMerge = [Tok]() {
if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
return false;
const FormatToken *Next = Tok->getNextNonComment();
return !Next || Next->is(tok::semi);
};
if (ShouldMerge()) {
// We merge empty blocks even if the line exceeds the column limit.
Tok->SpacesRequiredBefore =
(Style.SpaceInEmptyBlock || Line.Last->is(tok::comment)) ? 1 : 0;
Tok->CanBreakBefore = true;
return 1;
} else if (Limit != 0 && !Line.startsWithNamespace() &&
!startsExternCBlock(Line)) {
// We don't merge short records.
if (isRecordLBrace(*Line.Last))
return 0;
// Check that we still have three lines and they fit into the limit.
if (I + 2 == E || I[2]->Type == LT_Invalid)
return 0;
Limit = limitConsideringMacros(I + 2, E, Limit);
if (!nextTwoLinesFitInto(I, Limit))
return 0;
// Second, check that the next line does not contain any braces - if it
// does, readability declines when putting it into a single line.
if (I[1]->Last->is(TT_LineComment))
return 0;
do {
if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
return 0;
Tok = Tok->Next;
} while (Tok);
// Last, check that the third line starts with a closing brace.
Tok = I[2]->First;
if (Tok->isNot(tok::r_brace))
return 0;
// Don't merge "if (a) { .. } else {".
if (Tok->Next && Tok->Next->is(tok::kw_else))
return 0;
// Don't merge a trailing multi-line control statement block like:
// } else if (foo &&
// bar)
// { <-- current Line
// baz();
// }
if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) &&
Style.BraceWrapping.AfterControlStatement ==
FormatStyle::BWACS_MultiLine) {
return 0;
}
return 2;
}
} else if (I[1]->First->is(tok::l_brace)) {
if (I[1]->Last->is(TT_LineComment))
return 0;
// Check for Limit <= 2 to account for the " {".
if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
return 0;
Limit -= 2;
unsigned MergedLines = 0;
if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
(I[1]->First == I[1]->Last && I + 2 != E &&
I[2]->First->is(tok::r_brace))) {
MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
// If we managed to merge the block, count the statement header, which
// is on a separate line.
if (MergedLines > 0)
++MergedLines;
}
return MergedLines;
}
return 0;
}
/// Returns the modified column limit for \p I if it is inside a macro and
/// needs a trailing '\'.
unsigned
limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
unsigned Limit) {
if (I[0]->InPPDirective && I + 1 != E &&
!I[1]->First->HasUnescapedNewline && I[1]->First->isNot(tok::eof)) {
return Limit < 2 ? 0 : Limit - 2;
}
return Limit;
}
bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
unsigned Limit) {
if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
return false;
return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
}
bool containsMustBreak(const AnnotatedLine *Line) {
assert(Line->First);
// Ignore the first token, because in this situation, it applies more to the
// last token of the previous line.
for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next)
if (Tok->MustBreakBefore)
return true;
return false;
}
void join(AnnotatedLine &A, const AnnotatedLine &B) {
assert(!A.Last->Next);
assert(!B.First->Previous);
if (B.Affected)
A.Affected = true;
A.Last->Next = B.First;
B.First->Previous = A.Last;
B.First->CanBreakBefore = true;
unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
Tok->TotalLength += LengthA;
A.Last = Tok;
}
}
const FormatStyle &Style;
const AdditionalKeywords &Keywords;
const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
};
static void markFinalized(FormatToken *Tok) {
if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
tok::pp_else, tok::pp_endif)) {
Tok = Tok->Next;
}
for (; Tok; Tok = Tok->Next) {
if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
// In the first pass we format all macro arguments in the expanded token
// stream. Instead of finalizing the macro arguments, we mark that they
// will be modified as unexpanded arguments (as part of the macro call
// formatting) in the next pass.
Tok->MacroCtx->Role = MR_UnexpandedArg;
// Reset whether spaces are required before this token, as that is context
// dependent, and that context may change when formatting the macro call.
// For example, given M(x) -> 2 * x, and the macro call M(var),
// the token 'var' will have SpacesRequiredBefore = 1 after being
// formatted as part of the expanded macro, but SpacesRequiredBefore = 0
// for its position within the macro call.
Tok->SpacesRequiredBefore = 0;
} else {
Tok->Finalized = true;
}
}
}
#ifndef NDEBUG
static void printLineState(const LineState &State) {
llvm::dbgs() << "State: ";
for (const ParenState &P : State.Stack) {
llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
<< P.LastSpace << "|" << P.NestedBlockIndent << " ";
}
llvm::dbgs() << State.NextToken->TokenText << "\n";
}
#endif
/// Base class for classes that format one \c AnnotatedLine.
class LineFormatter {
public:
LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
const FormatStyle &Style,
UnwrappedLineFormatter *BlockFormatter)
: Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
BlockFormatter(BlockFormatter) {}
virtual ~LineFormatter() {}
/// Formats an \c AnnotatedLine and returns the penalty.
///
/// If \p DryRun is \c false, directly applies the changes.
virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
unsigned FirstStartColumn, bool DryRun) = 0;
protected:
/// If the \p State's next token is an r_brace closing a nested block,
/// format the nested block before it.
///