-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathContinuationIndenter.cpp
2944 lines (2741 loc) · 126 KB
/
ContinuationIndenter.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
//===--- ContinuationIndenter.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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the continuation indenter.
///
//===----------------------------------------------------------------------===//
#include "ContinuationIndenter.h"
#include "BreakableToken.h"
#include "FormatInternal.h"
#include "FormatToken.h"
#include "WhitespaceManager.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Format/Format.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Debug.h"
#include <optional>
#define DEBUG_TYPE "format-indenter"
namespace clang {
namespace format {
// Returns true if a TT_SelectorName should be indented when wrapped,
// false otherwise.
static bool shouldIndentWrappedSelectorName(const FormatStyle &Style,
LineType LineType) {
return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
}
// Returns true if a binary operator following \p Tok should be unindented when
// the style permits it.
static bool shouldUnindentNextOperator(const FormatToken &Tok) {
const FormatToken *Previous = Tok.getPreviousNonComment();
return Previous && (Previous->getPrecedence() == prec::Assignment ||
Previous->isOneOf(tok::kw_return, TT_RequiresClause));
}
// Returns the length of everything up to the first possible line break after
// the ), ], } or > matching \c Tok.
static unsigned getLengthToMatchingParen(const FormatToken &Tok,
ArrayRef<ParenState> Stack) {
// Normally whether or not a break before T is possible is calculated and
// stored in T.CanBreakBefore. Braces, array initializers and text proto
// messages like `key: < ... >` are an exception: a break is possible
// before a closing brace R if a break was inserted after the corresponding
// opening brace. The information about whether or not a break is needed
// before a closing brace R is stored in the ParenState field
// S.BreakBeforeClosingBrace where S is the state that R closes.
//
// In order to decide whether there can be a break before encountered right
// braces, this implementation iterates over the sequence of tokens and over
// the paren stack in lockstep, keeping track of the stack level which visited
// right braces correspond to in MatchingStackIndex.
//
// For example, consider:
// L. <- line number
// 1. {
// 2. {1},
// 3. {2},
// 4. {{3}}}
// ^ where we call this method with this token.
// The paren stack at this point contains 3 brace levels:
// 0. { at line 1, BreakBeforeClosingBrace: true
// 1. first { at line 4, BreakBeforeClosingBrace: false
// 2. second { at line 4, BreakBeforeClosingBrace: false,
// where there might be fake parens levels in-between these levels.
// The algorithm will start at the first } on line 4, which is the matching
// brace of the initial left brace and at level 2 of the stack. Then,
// examining BreakBeforeClosingBrace: false at level 2, it will continue to
// the second } on line 4, and will traverse the stack downwards until it
// finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
// false at level 1, it will continue to the third } on line 4 and will
// traverse the stack downwards until it finds the matching { on level 0.
// Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
// will stop and will use the second } on line 4 to determine the length to
// return, as in this example the range will include the tokens: {3}}
//
// The algorithm will only traverse the stack if it encounters braces, array
// initializer squares or text proto angle brackets.
if (!Tok.MatchingParen)
return 0;
FormatToken *End = Tok.MatchingParen;
// Maintains a stack level corresponding to the current End token.
int MatchingStackIndex = Stack.size() - 1;
// Traverses the stack downwards, looking for the level to which LBrace
// corresponds. Returns either a pointer to the matching level or nullptr if
// LParen is not found in the initial portion of the stack up to
// MatchingStackIndex.
auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
--MatchingStackIndex;
return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr;
};
for (; End->Next; End = End->Next) {
if (End->Next->CanBreakBefore)
break;
if (!End->Next->closesScope())
continue;
if (End->Next->MatchingParen &&
End->Next->MatchingParen->isOneOf(
tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
const ParenState *State = FindParenState(End->Next->MatchingParen);
if (State && State->BreakBeforeClosingBrace)
break;
}
}
return End->TotalLength - Tok.TotalLength + 1;
}
static unsigned getLengthToNextOperator(const FormatToken &Tok) {
if (!Tok.NextOperator)
return 0;
return Tok.NextOperator->TotalLength - Tok.TotalLength;
}
// Returns \c true if \c Tok is the "." or "->" of a call and starts the next
// segment of a builder type call.
static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) {
return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope();
}
// Returns \c true if \c Token in an alignable binary operator
static bool isAlignableBinaryOperator(const FormatToken &Token) {
// No need to align binary operators that only have two operands.
bool HasTwoOperands = Token.OperatorIndex == 0 && !Token.NextOperator;
return Token.is(TT_BinaryOperator) && !HasTwoOperands &&
Token.getPrecedence() > prec::Conditional &&
Token.getPrecedence() < prec::PointerToMember;
}
// Returns \c true if \c Current starts the next operand in a binary operation.
static bool startsNextOperand(const FormatToken &Current) {
assert(Current.Previous);
const auto &Previous = *Current.Previous;
return isAlignableBinaryOperator(Previous) && !Current.isTrailingComment();
}
// Returns \c true if \c Current is a binary operation that must break.
static bool mustBreakBinaryOperation(const FormatToken &Current,
const FormatStyle &Style) {
return Style.BreakBinaryOperations != FormatStyle::BBO_Never &&
Current.CanBreakBefore &&
(Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None
? startsNextOperand
: isAlignableBinaryOperator)(Current);
}
static bool opensProtoMessageField(const FormatToken &LessTok,
const FormatStyle &Style) {
if (LessTok.isNot(tok::less))
return false;
return Style.Language == FormatStyle::LK_TextProto ||
(Style.Language == FormatStyle::LK_Proto &&
(LessTok.NestingLevel > 0 ||
(LessTok.Previous && LessTok.Previous->is(tok::equal))));
}
// Returns the delimiter of a raw string literal, or std::nullopt if TokenText
// is not the text of a raw string literal. The delimiter could be the empty
// string. For example, the delimiter of R"deli(cont)deli" is deli.
static std::optional<StringRef> getRawStringDelimiter(StringRef TokenText) {
if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'.
|| !TokenText.starts_with("R\"") || !TokenText.ends_with("\"")) {
return std::nullopt;
}
// A raw string starts with 'R"<delimiter>(' and delimiter is ascii and has
// size at most 16 by the standard, so the first '(' must be among the first
// 19 bytes.
size_t LParenPos = TokenText.substr(0, 19).find_first_of('(');
if (LParenPos == StringRef::npos)
return std::nullopt;
StringRef Delimiter = TokenText.substr(2, LParenPos - 2);
// Check that the string ends in ')Delimiter"'.
size_t RParenPos = TokenText.size() - Delimiter.size() - 2;
if (TokenText[RParenPos] != ')')
return std::nullopt;
if (!TokenText.substr(RParenPos + 1).starts_with(Delimiter))
return std::nullopt;
return Delimiter;
}
// Returns the canonical delimiter for \p Language, or the empty string if no
// canonical delimiter is specified.
static StringRef
getCanonicalRawStringDelimiter(const FormatStyle &Style,
FormatStyle::LanguageKind Language) {
for (const auto &Format : Style.RawStringFormats)
if (Format.Language == Language)
return StringRef(Format.CanonicalDelimiter);
return "";
}
RawStringFormatStyleManager::RawStringFormatStyleManager(
const FormatStyle &CodeStyle) {
for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
std::optional<FormatStyle> LanguageStyle =
CodeStyle.GetLanguageStyle(RawStringFormat.Language);
if (!LanguageStyle) {
FormatStyle PredefinedStyle;
if (!getPredefinedStyle(RawStringFormat.BasedOnStyle,
RawStringFormat.Language, &PredefinedStyle)) {
PredefinedStyle = getLLVMStyle();
PredefinedStyle.Language = RawStringFormat.Language;
}
LanguageStyle = PredefinedStyle;
}
LanguageStyle->ColumnLimit = CodeStyle.ColumnLimit;
for (StringRef Delimiter : RawStringFormat.Delimiters)
DelimiterStyle.insert({Delimiter, *LanguageStyle});
for (StringRef EnclosingFunction : RawStringFormat.EnclosingFunctions)
EnclosingFunctionStyle.insert({EnclosingFunction, *LanguageStyle});
}
}
std::optional<FormatStyle>
RawStringFormatStyleManager::getDelimiterStyle(StringRef Delimiter) const {
auto It = DelimiterStyle.find(Delimiter);
if (It == DelimiterStyle.end())
return std::nullopt;
return It->second;
}
std::optional<FormatStyle>
RawStringFormatStyleManager::getEnclosingFunctionStyle(
StringRef EnclosingFunction) const {
auto It = EnclosingFunctionStyle.find(EnclosingFunction);
if (It == EnclosingFunctionStyle.end())
return std::nullopt;
return It->second;
}
ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style,
const AdditionalKeywords &Keywords,
const SourceManager &SourceMgr,
WhitespaceManager &Whitespaces,
encoding::Encoding Encoding,
bool BinPackInconclusiveFunctions)
: Style(Style), Keywords(Keywords), SourceMgr(SourceMgr),
Whitespaces(Whitespaces), Encoding(Encoding),
BinPackInconclusiveFunctions(BinPackInconclusiveFunctions),
CommentPragmasRegex(Style.CommentPragmas), RawStringFormats(Style) {}
LineState ContinuationIndenter::getInitialState(unsigned FirstIndent,
unsigned FirstStartColumn,
const AnnotatedLine *Line,
bool DryRun) {
LineState State;
State.FirstIndent = FirstIndent;
if (FirstStartColumn && Line->First->NewlinesBefore == 0)
State.Column = FirstStartColumn;
else
State.Column = FirstIndent;
// With preprocessor directive indentation, the line starts on column 0
// since it's indented after the hash, but FirstIndent is set to the
// preprocessor indent.
if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
(Line->Type == LT_PreprocessorDirective ||
Line->Type == LT_ImportStatement)) {
State.Column = 0;
}
State.Line = Line;
State.NextToken = Line->First;
State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent,
/*AvoidBinPacking=*/false,
/*NoLineBreak=*/false));
State.NoContinuation = false;
State.StartOfStringLiteral = 0;
State.NoLineBreak = false;
State.StartOfLineLevel = 0;
State.LowestLevelOnLine = 0;
State.IgnoreStackForComparison = false;
if (Style.Language == FormatStyle::LK_TextProto) {
// We need this in order to deal with the bin packing of text fields at
// global scope.
auto &CurrentState = State.Stack.back();
CurrentState.AvoidBinPacking = true;
CurrentState.BreakBeforeParameter = true;
CurrentState.AlignColons = false;
}
// The first token has already been indented and thus consumed.
moveStateToNextToken(State, DryRun, /*Newline=*/false);
return State;
}
bool ContinuationIndenter::canBreak(const LineState &State) {
const FormatToken &Current = *State.NextToken;
const FormatToken &Previous = *Current.Previous;
const auto &CurrentState = State.Stack.back();
assert(&Previous == Current.Previous);
if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace &&
Current.closesBlockOrBlockTypeList(Style))) {
return false;
}
// The opening "{" of a braced list has to be on the same line as the first
// element if it is nested in another braced init list or function call.
if (!Current.MustBreakBefore && Previous.is(tok::l_brace) &&
Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) &&
Previous.Previous &&
Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) {
return false;
}
// This prevents breaks like:
// ...
// SomeParameter, OtherParameter).DoSomething(
// ...
// As they hide "DoSomething" and are generally bad for readability.
if (Previous.opensScope() && Previous.isNot(tok::l_brace) &&
State.LowestLevelOnLine < State.StartOfLineLevel &&
State.LowestLevelOnLine < Current.NestingLevel) {
return false;
}
if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder)
return false;
// Don't create a 'hanging' indent if there are multiple blocks in a single
// statement and we are aligning lambda blocks to their signatures.
if (Previous.is(tok::l_brace) && State.Stack.size() > 1 &&
State.Stack[State.Stack.size() - 2].NestedBlockInlined &&
State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks &&
Style.LambdaBodyIndentation == FormatStyle::LBI_Signature) {
return false;
}
// Don't break after very short return types (e.g. "void") as that is often
// unexpected.
if (Current.is(TT_FunctionDeclarationName)) {
if (Style.BreakAfterReturnType == FormatStyle::RTBS_None &&
State.Column < 6) {
return false;
}
if (Style.BreakAfterReturnType == FormatStyle::RTBS_ExceptShortType) {
assert(State.Column >= State.FirstIndent);
if (State.Column - State.FirstIndent < 6)
return false;
}
}
// Don't break between function parameter keywords and parameter names.
if (Previous.is(TT_FunctionParameterKeyword) && Current.is(TT_StartOfName))
return false;
// Don't allow breaking before a closing brace of a block-indented braced list
// initializer if there isn't already a break.
if (Current.is(tok::r_brace) && Current.MatchingParen &&
Current.isBlockIndentedInitRBrace(Style)) {
return CurrentState.BreakBeforeClosingBrace;
}
// Allow breaking before the right parens with block indentation if there was
// a break after the left parens, which is tracked by BreakBeforeClosingParen.
if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent &&
Current.is(tok::r_paren)) {
return CurrentState.BreakBeforeClosingParen;
}
if (Style.BreakBeforeTemplateCloser && Current.is(TT_TemplateCloser))
return CurrentState.BreakBeforeClosingAngle;
// If binary operators are moved to the next line (including commas for some
// styles of constructor initializers), that's always ok.
if (!Current.isOneOf(TT_BinaryOperator, tok::comma) &&
// Allow breaking opening brace of lambdas (when passed as function
// arguments) to a new line when BeforeLambdaBody brace wrapping is
// enabled.
(!Style.BraceWrapping.BeforeLambdaBody ||
Current.isNot(TT_LambdaLBrace)) &&
CurrentState.NoLineBreakInOperand) {
return false;
}
if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr))
return false;
if (Current.is(TT_ConditionalExpr) && Previous.is(tok::r_paren) &&
Previous.MatchingParen && Previous.MatchingParen->Previous &&
Previous.MatchingParen->Previous->MatchingParen &&
Previous.MatchingParen->Previous->MatchingParen->is(TT_LambdaLBrace)) {
// We have a lambda within a conditional expression, allow breaking here.
assert(Previous.MatchingParen->Previous->is(tok::r_brace));
return true;
}
return !State.NoLineBreak && !CurrentState.NoLineBreak;
}
bool ContinuationIndenter::mustBreak(const LineState &State) {
const FormatToken &Current = *State.NextToken;
const FormatToken &Previous = *Current.Previous;
const auto &CurrentState = State.Stack.back();
if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
return LambdaBodyLength > getColumnLimit(State);
}
if (Current.MustBreakBefore ||
(Current.is(TT_InlineASMColon) &&
(Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_Always ||
(Style.BreakBeforeInlineASMColon == FormatStyle::BBIAS_OnlyMultiline &&
Style.ColumnLimit > 0)))) {
return true;
}
if (CurrentState.BreakBeforeClosingBrace &&
(Current.closesBlockOrBlockTypeList(Style) ||
(Current.is(tok::r_brace) &&
Current.isBlockIndentedInitRBrace(Style)))) {
return true;
}
if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
return true;
if (CurrentState.BreakBeforeClosingAngle && Current.is(TT_TemplateCloser))
return true;
if (Style.Language == FormatStyle::LK_ObjC &&
Style.ObjCBreakBeforeNestedBlockParam &&
Current.ObjCSelectorNameParts > 1 &&
Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) {
return true;
}
// Avoid producing inconsistent states by requiring breaks where they are not
// permitted for C# generic type constraints.
if (CurrentState.IsCSharpGenericTypeConstraint &&
Previous.isNot(TT_CSharpGenericTypeConstraintComma)) {
return false;
}
if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
// FIXME: This is a temporary workaround for the case where clang-format
// sets BreakBeforeParameter to avoid bin packing and this creates a
// completely unnecessary line break after a template type that isn't
// line-wrapped.
(Previous.NestingLevel == 1 ||
Style.BinPackParameters == FormatStyle::BPPS_BinPack)) ||
(Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
Previous.isNot(tok::question)) ||
(!Style.BreakBeforeTernaryOperators &&
Previous.is(TT_ConditionalExpr))) &&
CurrentState.BreakBeforeParameter && !Current.isTrailingComment() &&
!Current.isOneOf(tok::r_paren, tok::r_brace)) {
return true;
}
if (CurrentState.IsChainedConditional &&
((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) &&
Current.is(tok::colon)) ||
(!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) &&
Previous.is(tok::colon)))) {
return true;
}
if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) ||
(Previous.is(TT_ArrayInitializerLSquare) &&
Previous.ParameterCount > 1) ||
opensProtoMessageField(Previous, Style)) &&
Style.ColumnLimit > 0 &&
getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 >
getColumnLimit(State)) {
return true;
}
const FormatToken &BreakConstructorInitializersToken =
Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon
? Previous
: Current;
if (BreakConstructorInitializersToken.is(TT_CtorInitializerColon) &&
(State.Column + State.Line->Last->TotalLength - Previous.TotalLength >
getColumnLimit(State) ||
CurrentState.BreakBeforeParameter) &&
((!Current.isTrailingComment() && Style.ColumnLimit > 0) ||
Current.NewlinesBefore > 0)) {
return true;
}
if (Current.is(TT_ObjCMethodExpr) && Previous.isNot(TT_SelectorName) &&
State.Line->startsWith(TT_ObjCMethodSpecifier)) {
return true;
}
if (Current.is(TT_SelectorName) && Previous.isNot(tok::at) &&
CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter &&
(Style.ObjCBreakBeforeNestedBlockParam ||
!Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) {
return true;
}
unsigned NewLineColumn = getNewLineColumn(State);
if (Current.isMemberAccess() && Style.ColumnLimit != 0 &&
State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit &&
(State.Column > NewLineColumn ||
Current.NestingLevel < State.StartOfLineLevel)) {
return true;
}
if (startsSegmentOfBuilderTypeCall(Current) &&
(CurrentState.CallContinuation != 0 ||
CurrentState.BreakBeforeParameter) &&
// JavaScript is treated different here as there is a frequent pattern:
// SomeFunction(function() {
// ...
// }.bind(...));
// FIXME: We should find a more generic solution to this problem.
!(State.Column <= NewLineColumn && Style.isJavaScript()) &&
!(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) {
return true;
}
// If the template declaration spans multiple lines, force wrap before the
// function/class declaration.
if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter &&
Current.CanBreakBefore) {
return true;
}
if (State.Line->First->isNot(tok::kw_enum) && State.Column <= NewLineColumn)
return false;
if (Style.AlwaysBreakBeforeMultilineStrings &&
(NewLineColumn == State.FirstIndent + Style.ContinuationIndentWidth ||
Previous.is(tok::comma) || Current.NestingLevel < 2) &&
!Previous.isOneOf(tok::kw_return, tok::lessless, tok::at,
Keywords.kw_dollar) &&
!Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) &&
nextIsMultilineString(State)) {
return true;
}
// Using CanBreakBefore here and below takes care of the decision whether the
// current style uses wrapping before or after operators for the given
// operator.
if (Previous.is(TT_BinaryOperator) && Current.CanBreakBefore) {
const auto PreviousPrecedence = Previous.getPrecedence();
if (PreviousPrecedence != prec::Assignment &&
CurrentState.BreakBeforeParameter && !Current.isTrailingComment()) {
const bool LHSIsBinaryExpr =
Previous.Previous && Previous.Previous->EndsBinaryExpression;
if (LHSIsBinaryExpr)
return true;
// If we need to break somewhere inside the LHS of a binary expression, we
// should also break after the operator. Otherwise, the formatting would
// hide the operator precedence, e.g. in:
// if (aaaaaaaaaaaaaa ==
// bbbbbbbbbbbbbb && c) {..
// For comparisons, we only apply this rule, if the LHS is a binary
// expression itself as otherwise, the line breaks seem superfluous.
// We need special cases for ">>" which we have split into two ">" while
// lexing in order to make template parsing easier.
const bool IsComparison =
(PreviousPrecedence == prec::Relational ||
PreviousPrecedence == prec::Equality ||
PreviousPrecedence == prec::Spaceship) &&
Previous.Previous &&
Previous.Previous->isNot(TT_BinaryOperator); // For >>.
if (!IsComparison)
return true;
}
} else if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore &&
CurrentState.BreakBeforeParameter) {
return true;
}
// Same as above, but for the first "<<" operator.
if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) &&
CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) {
return true;
}
if (Current.NestingLevel == 0 && !Current.isTrailingComment()) {
// Always break after "template <...>"(*) and leading annotations. This is
// only for cases where the entire line does not fit on a single line as a
// different LineFormatter would be used otherwise.
// *: Except when another option interferes with that, like concepts.
if (Previous.ClosesTemplateDeclaration) {
if (Current.is(tok::kw_concept)) {
switch (Style.BreakBeforeConceptDeclarations) {
case FormatStyle::BBCDS_Allowed:
break;
case FormatStyle::BBCDS_Always:
return true;
case FormatStyle::BBCDS_Never:
return false;
}
}
if (Current.is(TT_RequiresClause)) {
switch (Style.RequiresClausePosition) {
case FormatStyle::RCPS_SingleLine:
case FormatStyle::RCPS_WithPreceding:
return false;
default:
return true;
}
}
return Style.BreakTemplateDeclarations != FormatStyle::BTDS_No &&
(Style.BreakTemplateDeclarations != FormatStyle::BTDS_Leave ||
Current.NewlinesBefore > 0);
}
if (Previous.is(TT_FunctionAnnotationRParen) &&
State.Line->Type != LT_PreprocessorDirective) {
return true;
}
if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) &&
Current.isNot(TT_LeadingJavaAnnotation)) {
return true;
}
}
if (Style.isJavaScript() && Previous.is(tok::r_paren) &&
Previous.is(TT_JavaAnnotation)) {
// Break after the closing parenthesis of TypeScript decorators before
// functions, getters and setters.
static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
"function"};
if (BreakBeforeDecoratedTokens.contains(Current.TokenText))
return true;
}
if (Current.is(TT_FunctionDeclarationName) &&
!State.Line->ReturnTypeWrapped &&
// Don't break before a C# function when no break after return type.
(!Style.isCSharp() ||
Style.BreakAfterReturnType > FormatStyle::RTBS_ExceptShortType) &&
// Don't always break between a JavaScript `function` and the function
// name.
!Style.isJavaScript() && Previous.isNot(tok::kw_template) &&
CurrentState.BreakBeforeParameter) {
for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous)
if (Tok->FirstAfterPPLine || Tok->is(TT_LineComment))
return false;
return true;
}
// The following could be precomputed as they do not depend on the state.
// However, as they should take effect only if the UnwrappedLine does not fit
// into the ColumnLimit, they are checked here in the ContinuationIndenter.
if (Style.ColumnLimit != 0 && Previous.is(BK_Block) &&
Previous.is(tok::l_brace) &&
!Current.isOneOf(tok::r_brace, tok::comment)) {
return true;
}
if (Current.is(tok::lessless) &&
((Previous.is(tok::identifier) && Previous.TokenText == "endl") ||
(Previous.Tok.isLiteral() && (Previous.TokenText.ends_with("\\n\"") ||
Previous.TokenText == "\'\\n\'")))) {
return true;
}
if (Previous.is(TT_BlockComment) && Previous.IsMultiline)
return true;
if (State.NoContinuation)
return true;
return false;
}
unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline,
bool DryRun,
unsigned ExtraSpaces) {
const FormatToken &Current = *State.NextToken;
assert(State.NextToken->Previous);
const FormatToken &Previous = *State.NextToken->Previous;
assert(!State.Stack.empty());
State.NoContinuation = false;
if (Current.is(TT_ImplicitStringLiteral) &&
(!Previous.Tok.getIdentifierInfo() ||
Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
tok::pp_not_keyword)) {
unsigned EndColumn =
SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
if (Current.LastNewlineOffset != 0) {
// If there is a newline within this token, the final column will solely
// determined by the current end column.
State.Column = EndColumn;
} else {
unsigned StartColumn =
SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getBegin());
assert(EndColumn >= StartColumn);
State.Column += EndColumn - StartColumn;
}
moveStateToNextToken(State, DryRun, /*Newline=*/false);
return 0;
}
unsigned Penalty = 0;
if (Newline)
Penalty = addTokenOnNewLine(State, DryRun);
else
addTokenOnCurrentLine(State, DryRun, ExtraSpaces);
return moveStateToNextToken(State, DryRun, Newline) + Penalty;
}
void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun,
unsigned ExtraSpaces) {
FormatToken &Current = *State.NextToken;
assert(State.NextToken->Previous);
const FormatToken &Previous = *State.NextToken->Previous;
auto &CurrentState = State.Stack.back();
bool DisallowLineBreaksOnThisLine =
Style.LambdaBodyIndentation == FormatStyle::LBI_Signature &&
// Deal with lambda arguments in C++. The aim here is to ensure that we
// don't over-indent lambda function bodies when lambdas are passed as
// arguments to function calls. We do this by ensuring that either all
// arguments (including any lambdas) go on the same line as the function
// call, or we break before the first argument.
Style.isCpp() && [&] {
// For example, `/*Newline=*/false`.
if (Previous.is(TT_BlockComment) && Current.SpacesRequiredBefore == 0)
return false;
const auto *PrevNonComment = Current.getPreviousNonComment();
if (!PrevNonComment || PrevNonComment->isNot(tok::l_paren))
return false;
if (Current.isOneOf(tok::comment, tok::l_paren, TT_LambdaLSquare))
return false;
auto BlockParameterCount = PrevNonComment->BlockParameterCount;
if (BlockParameterCount == 0)
return false;
// Multiple lambdas in the same function call.
if (BlockParameterCount > 1)
return true;
// A lambda followed by another arg.
if (!PrevNonComment->Role)
return false;
auto Comma = PrevNonComment->Role->lastComma();
if (!Comma)
return false;
auto Next = Comma->getNextNonComment();
return Next &&
!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret);
}();
if (DisallowLineBreaksOnThisLine)
State.NoLineBreak = true;
if (Current.is(tok::equal) &&
(State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) &&
CurrentState.VariablePos == 0 &&
(!Previous.Previous ||
Previous.Previous->isNot(TT_DesignatedInitializerPeriod))) {
CurrentState.VariablePos = State.Column;
// Move over * and & if they are bound to the variable name.
const FormatToken *Tok = &Previous;
while (Tok && CurrentState.VariablePos >= Tok->ColumnWidth) {
CurrentState.VariablePos -= Tok->ColumnWidth;
if (Tok->SpacesRequiredBefore != 0)
break;
Tok = Tok->Previous;
}
if (Previous.PartOfMultiVariableDeclStmt)
CurrentState.LastSpace = CurrentState.VariablePos;
}
unsigned Spaces = Current.SpacesRequiredBefore + ExtraSpaces;
// Indent preprocessor directives after the hash if required.
int PPColumnCorrection = 0;
if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash &&
Previous.is(tok::hash) && State.FirstIndent > 0 &&
&Previous == State.Line->First &&
(State.Line->Type == LT_PreprocessorDirective ||
State.Line->Type == LT_ImportStatement)) {
Spaces += State.FirstIndent;
// For preprocessor indent with tabs, State.Column will be 1 because of the
// hash. This causes second-level indents onward to have an extra space
// after the tabs. We avoid this misalignment by subtracting 1 from the
// column value passed to replaceWhitespace().
if (Style.UseTab != FormatStyle::UT_Never)
PPColumnCorrection = -1;
}
if (!DryRun) {
Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces,
State.Column + Spaces + PPColumnCorrection,
/*IsAligned=*/false, State.Line->InMacroBody);
}
// If "BreakBeforeInheritanceComma" mode, don't break within the inheritance
// declaration unless there is multiple inheritance.
if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
Current.is(TT_InheritanceColon)) {
CurrentState.NoLineBreak = true;
}
if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon &&
Previous.is(TT_InheritanceColon)) {
CurrentState.NoLineBreak = true;
}
if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) {
unsigned MinIndent = std::max(
State.FirstIndent + Style.ContinuationIndentWidth, CurrentState.Indent);
unsigned FirstColonPos = State.Column + Spaces + Current.ColumnWidth;
if (Current.LongestObjCSelectorName == 0)
CurrentState.AlignColons = false;
else if (MinIndent + Current.LongestObjCSelectorName > FirstColonPos)
CurrentState.ColonPos = MinIndent + Current.LongestObjCSelectorName;
else
CurrentState.ColonPos = FirstColonPos;
}
// In "AlwaysBreak" or "BlockIndent" mode, enforce wrapping directly after the
// parenthesis by disallowing any further line breaks if there is no line
// break after the opening parenthesis. Don't break if it doesn't conserve
// columns.
auto IsOpeningBracket = [&](const FormatToken &Tok) {
auto IsStartOfBracedList = [&]() {
return Tok.is(tok::l_brace) && Tok.isNot(BK_Block) &&
Style.Cpp11BracedListStyle;
};
if (!Tok.isOneOf(tok::l_paren, TT_TemplateOpener, tok::l_square) &&
!IsStartOfBracedList()) {
return false;
}
if (!Tok.Previous)
return true;
if (Tok.Previous->isIf())
return Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak;
return !Tok.Previous->isOneOf(TT_CastRParen, tok::kw_for, tok::kw_while,
tok::kw_switch) &&
!(Style.isJavaScript() && Tok.Previous->is(Keywords.kw_await));
};
auto IsFunctionCallParen = [](const FormatToken &Tok) {
return Tok.is(tok::l_paren) && Tok.ParameterCount > 0 && Tok.Previous &&
Tok.Previous->is(tok::identifier);
};
auto IsInTemplateString = [this](const FormatToken &Tok) {
if (!Style.isJavaScript())
return false;
for (const auto *Prev = &Tok; Prev; Prev = Prev->Previous) {
if (Prev->is(TT_TemplateString) && Prev->opensScope())
return true;
if (Prev->opensScope() ||
(Prev->is(TT_TemplateString) && Prev->closesScope())) {
break;
}
}
return false;
};
// Identifies simple (no expression) one-argument function calls.
auto StartsSimpleOneArgList = [&](const FormatToken &TokAfterLParen) {
assert(TokAfterLParen.isNot(tok::comment) || TokAfterLParen.Next);
const auto &Tok =
TokAfterLParen.is(tok::comment) ? *TokAfterLParen.Next : TokAfterLParen;
if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
return false;
// Nested calls that involve `new` expressions also look like simple
// function calls, eg:
// - foo(new Bar())
// - foo(::new Bar())
if (Tok.is(tok::kw_new) || Tok.startsSequence(tok::coloncolon, tok::kw_new))
return true;
if (Tok.is(TT_UnaryOperator) ||
(Style.isJavaScript() &&
Tok.isOneOf(tok::ellipsis, Keywords.kw_await))) {
return true;
}
const auto *Previous = Tok.Previous;
if (!Previous || (!Previous->isOneOf(TT_FunctionDeclarationLParen,
TT_LambdaDefinitionLParen) &&
!IsFunctionCallParen(*Previous))) {
return true;
}
if (IsOpeningBracket(Tok) || IsInTemplateString(Tok))
return true;
const auto *Next = Tok.Next;
return !Next || Next->isMemberAccess() ||
Next->is(TT_FunctionDeclarationLParen) || IsFunctionCallParen(*Next);
};
if ((Style.AlignAfterOpenBracket == FormatStyle::BAS_AlwaysBreak ||
Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) &&
IsOpeningBracket(Previous) && State.Column > getNewLineColumn(State) &&
// Don't do this for simple (no expressions) one-argument function calls
// as that feels like needlessly wasting whitespace, e.g.:
//
// caaaaaaaaaaaall(
// caaaaaaaaaaaall(
// caaaaaaaaaaaall(
// caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa))));
// or
// caaaaaaaaaaaaaaaaaaaaal(
// new SomethingElseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee());
!StartsSimpleOneArgList(Current)) {
CurrentState.NoLineBreak = true;
}
if (Previous.is(TT_TemplateString) && Previous.opensScope())
CurrentState.NoLineBreak = true;
// Align following lines within parentheses / brackets if configured.
// Note: This doesn't apply to macro expansion lines, which are MACRO( , , )
// with args as children of the '(' and ',' tokens. It does not make sense to
// align the commas with the opening paren.
if (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign &&
!CurrentState.IsCSharpGenericTypeConstraint && Previous.opensScope() &&
Previous.isNot(TT_ObjCMethodExpr) && Previous.isNot(TT_RequiresClause) &&
Previous.isNot(TT_TableGenDAGArgOpener) &&
Previous.isNot(TT_TableGenDAGArgOpenerToBreak) &&
!(Current.MacroParent && Previous.MacroParent) &&
(Current.isNot(TT_LineComment) ||
Previous.isOneOf(BK_BracedInit, TT_VerilogMultiLineListLParen)) &&
!IsInTemplateString(Current)) {
CurrentState.Indent = State.Column + Spaces;
CurrentState.IsAligned = true;
}
if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style))
CurrentState.NoLineBreak = true;
if (mustBreakBinaryOperation(Current, Style))
CurrentState.NoLineBreak = true;
if (startsSegmentOfBuilderTypeCall(Current) &&
State.Column > getNewLineColumn(State)) {
CurrentState.ContainsUnwrappedBuilder = true;
}
if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java)
CurrentState.NoLineBreak = true;
if (Current.isMemberAccess() && Previous.is(tok::r_paren) &&
(Previous.MatchingParen &&
(Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) {
// If there is a function call with long parameters, break before trailing
// calls. This prevents things like:
// EXPECT_CALL(SomeLongParameter).Times(
// 2);
// We don't want to do this for short parameters as they can just be
// indexes.
CurrentState.NoLineBreak = true;
}
// Don't allow the RHS of an operator to be split over multiple lines unless
// there is a line-break right after the operator.
// Exclude relational operators, as there, it is always more desirable to
// have the LHS 'left' of the RHS.
const FormatToken *P = Current.getPreviousNonComment();
if (Current.isNot(tok::comment) && P &&
(P->isOneOf(TT_BinaryOperator, tok::comma) ||
(P->is(TT_ConditionalExpr) && P->is(tok::colon))) &&
!P->isOneOf(TT_OverloadedOperator, TT_CtorInitializerComma) &&
P->getPrecedence() != prec::Assignment &&
P->getPrecedence() != prec::Relational &&
P->getPrecedence() != prec::Spaceship) {
bool BreakBeforeOperator =
P->MustBreakBefore || P->is(tok::lessless) ||
(P->is(TT_BinaryOperator) &&
Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None) ||
(P->is(TT_ConditionalExpr) && Style.BreakBeforeTernaryOperators);
// Don't do this if there are only two operands. In these cases, there is
// always a nice vertical separation between them and the extra line break
// does not help.
bool HasTwoOperands = P->OperatorIndex == 0 && !P->NextOperator &&
P->isNot(TT_ConditionalExpr);
if ((!BreakBeforeOperator &&
!(HasTwoOperands &&
Style.AlignOperands != FormatStyle::OAS_DontAlign)) ||
(!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) {
CurrentState.NoLineBreakInOperand = true;
}
}
State.Column += Spaces;
if (Current.isNot(tok::comment) && Previous.is(tok::l_paren) &&
Previous.Previous &&
(Previous.Previous->is(tok::kw_for) || Previous.Previous->isIf())) {
// Treat the condition inside an if as if it was a second function
// parameter, i.e. let nested calls have a continuation indent.
CurrentState.LastSpace = State.Column;
CurrentState.NestedBlockIndent = State.Column;
} else if (!Current.isOneOf(tok::comment, tok::caret) &&
((Previous.is(tok::comma) &&
Previous.isNot(TT_OverloadedOperator)) ||
(Previous.is(tok::colon) && Previous.is(TT_ObjCMethodExpr)))) {
CurrentState.LastSpace = State.Column;
} else if (Previous.is(TT_CtorInitializerColon) &&
(!Current.isTrailingComment() || Current.NewlinesBefore > 0) &&
Style.BreakConstructorInitializers ==
FormatStyle::BCIS_AfterColon) {
CurrentState.Indent = State.Column;
CurrentState.LastSpace = State.Column;
} else if (Previous.isOneOf(TT_ConditionalExpr, TT_CtorInitializerColon)) {
CurrentState.LastSpace = State.Column;
} else if (Previous.is(TT_BinaryOperator) &&
((Previous.getPrecedence() != prec::Assignment &&
(Previous.isNot(tok::lessless) || Previous.OperatorIndex != 0 ||
Previous.NextOperator)) ||
Current.StartsBinaryExpression)) {