15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
33 return C.Tok->IndentLevel;
41 return SourceMgr.isBeforeInTranslationUnit(
46 SourceMgr.isBeforeInTranslationUnit(
72 unsigned StartOfTokenColumn,
75 unsigned IndentedFromColumn) {
80 Spaces, StartOfTokenColumn, IndentedFromColumn,
82 InPPDirective && !
Tok.IsFirst,
91 Tok,
false,
Tok.WhitespaceRange, 0,
92 Tok.OriginalColumn, 0,
Tok.NewlinesBefore,
"",
"",
93 nullptr, InPPDirective && !
Tok.IsFirst,
99 return Replaces.add(Replacement);
103 size_t LF =
Text.count(
'\n');
104 size_t CR =
Text.count(
'\r') * 2;
105 return LF == CR ? DefaultToCRLF : CR > LF;
110 StringRef PreviousPostfix, StringRef CurrentPrefix,
bool InPPDirective,
119 PreviousPostfix, CurrentPrefix,
120 &
Tok, InPPDirective && !
Tok.IsFirst,
129 calculateLineBreakInformation();
130 alignConsecutiveMacros();
131 alignConsecutiveShortCaseStatements(
true);
132 alignConsecutiveShortCaseStatements(
false);
133 alignConsecutiveDeclarations();
134 alignConsecutiveBitFields();
135 alignConsecutiveAssignments();
136 if (Style.isTableGen()) {
137 alignConsecutiveTableGenBreakingDAGArgColons();
138 alignConsecutiveTableGenCondOperatorColons();
139 alignConsecutiveTableGenDefinitions();
141 alignChainedConditionals();
142 alignTrailingComments();
143 alignEscapedNewlines();
144 alignArrayInitializers();
150void WhitespaceManager::calculateLineBreakInformation() {
151 Changes[0].PreviousEndOfTokenColumn = 0;
152 Change *LastOutsideTokenChange = &Changes[0];
153 for (
unsigned I = 1, e = Changes.size(); I != e; ++I) {
154 auto &
C = Changes[I];
155 auto &P = Changes[I - 1];
156 auto &PrevTokLength = P.TokenLength;
157 const auto *PP = I > 1 ? &Changes[I - 2] :
nullptr;
159 C.OriginalWhitespaceRange.getBegin();
161 P.OriginalWhitespaceRange.getEnd();
162 unsigned OriginalWhitespaceStartOffset =
163 SourceMgr.getFileOffset(OriginalWhitespaceStart);
164 unsigned PreviousOriginalWhitespaceEndOffset =
165 SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
166 assert(PreviousOriginalWhitespaceEndOffset <=
167 OriginalWhitespaceStartOffset);
168 const char *
const PreviousOriginalWhitespaceEndData =
169 SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
170 StringRef
Text(PreviousOriginalWhitespaceEndData,
171 SourceMgr.getCharacterData(OriginalWhitespaceStart) -
172 PreviousOriginalWhitespaceEndData);
194 auto NewlinePos =
Text.find_first_of(
'\n');
195 if (NewlinePos == StringRef::npos) {
196 PrevTokLength = OriginalWhitespaceStartOffset -
197 PreviousOriginalWhitespaceEndOffset +
198 C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size();
199 if (!P.IsInsideToken)
200 PrevTokLength = std::min(PrevTokLength, P.Tok->ColumnWidth);
202 PrevTokLength = NewlinePos + P.CurrentLinePrefix.size();
207 if (P.IsInsideToken && P.NewlinesBefore == 0)
208 LastOutsideTokenChange->TokenLength += PrevTokLength + P.Spaces;
210 LastOutsideTokenChange = &P;
212 C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + PrevTokLength;
214 P.IsTrailingComment =
215 (
C.NewlinesBefore > 0 ||
C.Tok->is(tok::eof) ||
216 (
C.IsInsideToken &&
C.Tok->is(tok::comment))) &&
217 P.Tok->is(tok::comment) &&
218 (P.NewlinesBefore == 0 || !PP || PP->IsTrailingComment) &&
249 OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
253 Changes.back().TokenLength = 0;
254 Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
256 const WhitespaceManager::Change *LastBlockComment =
nullptr;
257 for (
auto &
Change : Changes) {
267 LastBlockComment = &
Change;
274 LastBlockComment =
nullptr;
282 SmallVector<bool, 16> ScopeStack;
283 int ConditionalsLevel = 0;
284 for (
auto &
Change : Changes) {
286 bool isNestedConditional =
291 if (isNestedConditional)
293 ScopeStack.push_back(isNestedConditional);
299 if (ScopeStack.pop_back_val())
310 auto &FirstChange = Changes[Start];
311 const int ColumnChange = Spaces - FirstChange.Spaces;
313 if (ColumnChange == 0)
316 FirstChange.Spaces += ColumnChange;
317 FirstChange.StartOfTokenColumn += ColumnChange;
319 for (
auto I = Start + 1; I < Changes.size(); I++) {
320 auto &Change = Changes[I];
322 Change.PreviousEndOfTokenColumn += ColumnChange;
324 if (Change.NewlinesBefore > 0)
327 Change.StartOfTokenColumn += ColumnChange;
337 assert(Delta > 0 || (
abs(Delta) <= Changes[Start].Spaces));
347 unsigned Column,
bool RightJustify,
350 unsigned OriginalMatchColumn = 0;
378 for (
unsigned i = Start; i != End; ++i) {
379 auto &CurrentChange = Changes[i];
380 if (!Matches.empty() && Matches[0] < i)
381 Matches.consume_front();
382 assert(Matches.empty() || Matches[0] >= i);
383 while (!ScopeStack.empty() &&
384 CurrentChange.indentAndNestingLevel() < ScopeStack.back()) {
385 ScopeStack.pop_back();
389 if (ScopeStack.size() == 1u && CurrentChange.NewlinesBefore != 0u &&
390 CurrentChange.indentAndNestingLevel() > ScopeStack[0] &&
391 CurrentChange.IndentedFromColumn < OriginalMatchColumn) {
392 ScopeStack.push_back(CurrentChange.indentAndNestingLevel());
395 bool InsideNestedScope =
396 !ScopeStack.empty() &&
397 (CurrentChange.indentAndNestingLevel() > ScopeStack[0] ||
398 (CurrentChange.indentAndNestingLevel() == ScopeStack[0] &&
399 CurrentChange.IndentedFromColumn >= OriginalMatchColumn));
401 if (CurrentChange.NewlinesBefore > 0 && !InsideNestedScope)
407 if (!Matches.empty() && Matches[0] == i) {
408 OriginalMatchColumn = CurrentChange.StartOfTokenColumn;
409 Shift =
Column - (RightJustify ? CurrentChange.TokenLength : 0) -
410 CurrentChange.StartOfTokenColumn;
411 ScopeStack = {CurrentChange.indentAndNestingLevel()};
420 if ((!Matches.empty() && Matches[0] == i) ||
421 (ScopeStack.size() == 1u && CurrentChange.NewlinesBefore > 0 &&
422 InsideNestedScope)) {
423 CurrentChange.IndentedFromColumn += Shift;
429 CurrentChange.Spaces >=
430 static_cast<int>(Changes[i].Tok->SpacesRequiredBefore) ||
431 CurrentChange.Tok->is(tok::eof));
435 if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
436 Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
437 CurrentChange.Spaces != 0 &&
438 CurrentChange.Tok->isNoneOf(tok::equal, tok::r_paren,
439 TT_TemplateCloser)) {
440 const bool ReferenceNotRightAligned =
441 Style.ReferenceAlignment != FormatStyle::RAS_Right &&
442 Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
446 assert(Changes[
Previous].
Tok->isPointerOrReference());
448 if (ReferenceNotRightAligned)
450 }
else if (Style.PointerAlignment != FormatStyle::PAS_Right) {
462enum class AlignStrategy {
Normal,
Macro, CaseBody, CaseColon };
505template <
typename F, AlignStrategy Strategy = AlignStrategy::Normal>
509 const FormatStyle::AlignConsecutiveStyle &ACS = {},
510 bool RightJustify =
false) {
521 unsigned WidthLeft = 0;
524 unsigned WidthAnchor = 0;
527 unsigned WidthRight = 0;
530 unsigned StartOfSequence = 0;
531 unsigned EndOfSequence = 0;
538 const auto IndentAndNestingLevel =
539 StartAt < Changes.size() ? Changes[StartAt].indentAndNestingLevel()
540 : std::tuple<unsigned, unsigned, unsigned>();
545 unsigned CommasBeforeLastMatch = 0;
546 unsigned CommasBeforeMatch = 0;
549 std::optional<unsigned> MatchingColumn;
552 bool LineIsComment =
true;
561 auto AlignCurrentSequence = [&] {
562 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
564 WidthLeft + WidthAnchor, RightJustify, MatchedIndices,
572 MatchedIndices.clear();
575 unsigned I = StartAt;
576 const auto E = Changes.size();
577 for (
const auto LoopEnd = Strategy == AlignStrategy::CaseBody ? E - 1 : E;
579 auto &CurrentChange = Changes[I];
580 if (CurrentChange.indentAndNestingLevel() < IndentAndNestingLevel)
583 if (CurrentChange.NewlinesBefore != 0) {
584 CommasBeforeMatch = 0;
588 bool EmptyLineBreak =
589 (CurrentChange.NewlinesBefore > 1) && !ACS.AcrossEmptyLines;
594 !MatchingColumn && !(LineIsComment && ACS.AcrossComments);
596 if (EmptyLineBreak || NoMatchBreak)
597 AlignCurrentSequence();
601 if (MatchingColumn && CurrentChange.IndentedFromColumn < *MatchingColumn)
602 MatchingColumn.reset();
603 LineIsComment =
true;
606 if (CurrentChange.Tok->isNot(tok::comment))
607 LineIsComment =
false;
609 if constexpr (Strategy == AlignStrategy::Normal) {
610 if (CurrentChange.Tok->is(tok::comma)) {
612 }
else if (CurrentChange.indentAndNestingLevel() >
613 IndentAndNestingLevel) {
616 Style, Matches, Changes, I, ACS, RightJustify);
622 if (!Matches(CurrentChange))
625 const auto IndexToAlign = Strategy == AlignStrategy::CaseBody ? I + 1 : I;
626 const auto &ChangeToAlign = Changes[IndexToAlign];
627 const auto [AlignTheToken,
628 ShiftAlignment] = [&]() -> std::pair<bool, bool> {
630 case AlignStrategy::CaseBody: {
631 if (ChangeToAlign.NewlinesBefore == 0)
632 return {
true,
false};
633 const auto *
Tok = ChangeToAlign.Tok;
634 if (
Tok->is(tok::comment) && ACS.AcrossComments)
635 Tok =
Tok->getNextNonComment();
636 return {
false,
Tok &&
Tok->isOneOf(tok::kw_case, tok::kw_default)};
638 case AlignStrategy::CaseColon: {
639 if (I + 1 == LoopEnd)
640 return {
true,
false};
641 const auto &NextChange = Changes[I + 1];
642 if (NextChange.NewlinesBefore == 0 ||
643 (CurrentChange.Tok->Next &&
644 CurrentChange.Tok->Next->isTrailingComment())) {
645 return {
true,
false};
647 const auto *
Tok = NextChange.Tok;
648 if (
Tok->is(tok::comment) && ACS.AcrossComments)
649 Tok =
Tok->getNextNonComment();
650 return {
Tok &&
Tok->isOneOf(tok::kw_case, tok::kw_default),
false};
653 return {
true,
false};
657 if (!AlignTheToken && !ShiftAlignment)
662 if ((ChangeToAlign.NewlinesBefore == 0U && MatchingColumn) ||
663 CommasBeforeMatch != CommasBeforeLastMatch) {
664 MatchedIndices.push_back(IndexToAlign);
665 AlignCurrentSequence();
668 CommasBeforeLastMatch = CommasBeforeMatch;
669 MatchingColumn = AlignTheToken ? ChangeToAlign.StartOfTokenColumn
670 : std::numeric_limits<unsigned>::max();
672 if (StartOfSequence == 0 && AlignTheToken)
673 StartOfSequence = IndexToAlign;
675 unsigned ChangeWidthLeft = ChangeToAlign.StartOfTokenColumn;
676 unsigned ChangeWidthAnchor = 0;
677 unsigned ChangeWidthRight = 0;
678 unsigned CurrentChangeWidthRight = 0;
679 if (!AlignTheToken) {
683 ChangeWidthLeft = CurrentChange.StartOfTokenColumn +
684 CurrentChange.TokenLength +
688 if (ACS.PadOperators)
689 ChangeWidthAnchor = ChangeToAlign.TokenLength;
691 ChangeWidthLeft += ChangeToAlign.TokenLength;
693 CurrentChangeWidthRight = ChangeToAlign.TokenLength;
694 const FormatToken *MatchingParenToEncounter =
nullptr;
695 for (
unsigned J = IndexToAlign + 1;
696 J != E && (Changes[J].NewlinesBefore == 0 ||
697 MatchingParenToEncounter || Changes[J].AlignedTo);
699 const auto &
Change = Changes[J];
702 if (
Tok->MatchingParen) {
703 if (
Tok->isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
704 TT_TemplateOpener) &&
705 !MatchingParenToEncounter) {
710 MatchingParenToEncounter =
Tok->MatchingParen;
711 }
else if (MatchingParenToEncounter ==
Tok->MatchingParen) {
712 MatchingParenToEncounter =
nullptr;
718 std::max(ChangeWidthRight, CurrentChangeWidthRight);
719 const auto ChangeWidthStart = ChangeWidthLeft + ChangeWidthAnchor;
730 CurrentChangeWidthRight =
Change.
Spaces - ChangeWidthStart;
744 ChangeWidthRight = std::max(ChangeWidthRight, CurrentChangeWidthRight);
748 unsigned NewLeft = std::max(ChangeWidthLeft, WidthLeft);
749 unsigned NewAnchor = std::max(ChangeWidthAnchor, WidthAnchor);
750 unsigned NewRight = std::max(ChangeWidthRight, WidthRight);
752 if (Style.ColumnLimit != 0 &&
753 Style.ColumnLimit < NewLeft + NewAnchor + NewRight) {
754 AlignCurrentSequence();
755 StartOfSequence = AlignTheToken ? IndexToAlign : 0;
756 WidthLeft = ChangeWidthLeft;
757 WidthAnchor = ChangeWidthAnchor;
758 WidthRight = ChangeWidthRight;
761 WidthAnchor = NewAnchor;
762 WidthRight = NewRight;
765 MatchedIndices.push_back(IndexToAlign);
770 for (EndOfSequence = I;
771 EndOfSequence < E && Changes[EndOfSequence].NewlinesBefore == 0;
774 AlignCurrentSequence();
780void WhitespaceManager::alignConsecutiveMacros() {
781 if (!Style.AlignConsecutiveMacros.Enabled)
784 auto AlignMacrosMatches = [](
const Change &
C) {
788 if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
791 Current = Current->Previous;
795 if (Current->is(tok::r_paren)) {
804 }
else if (Current->Next->SpacesRequiredBefore != 1) {
810 return Current->endsSequence(tok::identifier, tok::pp_define);
814 Style, AlignMacrosMatches, Changes, 0, Style.AlignConsecutiveMacros);
817void WhitespaceManager::alignConsecutiveAssignments() {
818 if (!Style.AlignConsecutiveAssignments.Enabled &&
819 !Style.AlignConsecutiveAssignments.EnumAssignments) {
827 if (
C.NewlinesBefore > 0)
831 if (&
C != &Changes.back() && (&
C + 1)->NewlinesBefore > 0)
835 if (Style.AlignConsecutiveAssignments.EnumAssignments &&
836 C.Tok->is(TT_EnumEqual)) {
840 if (!Style.AlignConsecutiveAssignments.Enabled)
848 return Style.AlignConsecutiveAssignments.AlignCompound
850 : (
C.Tok->is(tok::equal) ||
854 (Style.isVerilog() &&
C.Tok->is(tok::lessequal) &&
857 Changes, 0, Style.AlignConsecutiveAssignments,
861void WhitespaceManager::alignConsecutiveBitFields() {
862 alignConsecutiveColons(Style.AlignConsecutiveBitFields, TT_BitFieldColon);
865void WhitespaceManager::alignConsecutiveColons(
866 const FormatStyle::AlignConsecutiveStyle &AlignStyle,
TokenType Type) {
867 if (!AlignStyle.Enabled)
874 if (
C.NewlinesBefore > 0)
878 if (&
C != &Changes.back() && (&
C + 1)->NewlinesBefore > 0)
881 return C.Tok->is(
Type);
883 Changes, 0, AlignStyle);
886void WhitespaceManager::alignConsecutiveShortCaseStatements(
bool IsExpr) {
887 if (!Style.AlignConsecutiveShortCaseStatements.Enabled ||
888 !(IsExpr ? Style.AllowShortCaseExpressionOnASingleLine
889 : Style.AllowShortCaseLabelsOnASingleLine)) {
893 const auto Type = IsExpr ? TT_CaseLabelArrow : TT_CaseLabelColon;
894 const auto &Option = Style.AlignConsecutiveShortCaseStatements;
895 const bool AlignArrowOrColon =
896 IsExpr ? Option.AlignCaseArrows : Option.AlignCaseColons;
898 FormatStyle::AlignConsecutiveStyle AlignStyle{};
899 AlignStyle.AcrossComments = Option.AcrossComments;
900 AlignStyle.AcrossEmptyLines = Option.AcrossEmptyLines;
903 if (AlignArrowOrColon) {
905 Style, Matches, Changes, 0, AlignStyle);
908 Style, Matches, Changes, 0, AlignStyle);
912void WhitespaceManager::alignConsecutiveTableGenBreakingDAGArgColons() {
913 alignConsecutiveColons(Style.AlignConsecutiveTableGenBreakingDAGArgColons,
914 TT_TableGenDAGArgListColonToAlign);
917void WhitespaceManager::alignConsecutiveTableGenCondOperatorColons() {
918 alignConsecutiveColons(Style.AlignConsecutiveTableGenCondOperatorColons,
919 TT_TableGenCondOperatorColon);
922void WhitespaceManager::alignConsecutiveTableGenDefinitions() {
923 alignConsecutiveColons(Style.AlignConsecutiveTableGenDefinitionColons,
924 TT_InheritanceColon);
927void WhitespaceManager::alignConsecutiveDeclarations() {
928 if (!Style.AlignConsecutiveDeclarations.Enabled)
934 if (
C.Tok->is(TT_FunctionTypeLParen))
935 return Style.AlignConsecutiveDeclarations.AlignFunctionPointers;
936 if (
C.Tok->is(TT_FunctionDeclarationName))
937 return Style.AlignConsecutiveDeclarations.AlignFunctionDeclarations;
938 if (
C.Tok->isNot(TT_StartOfName))
940 if (
C.Tok->Previous &&
941 C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
945 if (
Next->is(tok::comment))
947 if (
Next->is(TT_PointerOrReference))
949 if (!
Next->Tok.getIdentifierInfo())
951 if (
Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
958 Changes, 0, Style.AlignConsecutiveDeclarations);
961void WhitespaceManager::alignChainedConditionals() {
962 if (Style.BreakBeforeTernaryOperators) {
967 return C.Tok->is(TT_ConditionalExpr) &&
968 ((
C.Tok->is(tok::question) && !
C.NewlinesBefore) ||
969 (
C.Tok->is(tok::colon) &&
C.Tok->Next &&
970 (
C.Tok->Next->FakeLParens.empty() ||
975 static auto AlignWrappedOperand = [](
Change const &
C) {
979 (
C.Tok->FakeLParens.empty() ||
986 if (AlignWrappedOperand(
C))
987 C.StartOfTokenColumn -= 2;
994 return (
C.Tok->is(TT_ConditionalExpr) &&
C.Tok->is(tok::question) &&
995 &
C != &Changes.back() && (&
C + 1)->NewlinesBefore == 0 &&
996 !(&
C + 1)->IsTrailingComment) ||
997 AlignWrappedOperand(
C);
1003void WhitespaceManager::alignTrailingComments() {
1004 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
1007 const int Size = Changes.size();
1012 int StartOfSequence = 0;
1013 bool BreakBeforeNext =
false;
1014 bool IsInPP = Changes.front().Tok->Tok.is(tok::hash);
1015 int NewLineThreshold = 1;
1016 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
1017 NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
1020 auto &
C = Changes[I];
1021 if (
C.StartOfBlockComment)
1023 if (
C.NewlinesBefore != 0) {
1025 const bool WasInPP = std::exchange(
1026 IsInPP,
C.Tok->Tok.is(tok::hash) || (IsInPP &&
C.IsTrailingComment) ||
1027 C.ContinuesPPDirective);
1028 if (IsInPP != WasInPP && !Style.AlignTrailingComments.AlignPPAndNotPP) {
1029 alignTrailingComments(StartOfSequence, I, MinColumn);
1032 StartOfSequence = I;
1036 if (!
C.IsTrailingComment)
1039 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1040 const int OriginalSpaces =
1041 C.OriginalWhitespaceRange.getEnd().getRawEncoding() -
1042 C.OriginalWhitespaceRange.getBegin().getRawEncoding() -
1043 C.Tok->LastNewlineOffset;
1044 assert(OriginalSpaces >= 0);
1045 const auto RestoredLineLength =
1046 C.StartOfTokenColumn +
C.TokenLength + OriginalSpaces;
1049 if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit > 0)
1053 C.NewlinesBefore > 0 ?
C.Tok->OriginalColumn : OriginalSpaces;
1054 setChangeSpaces(I, Spaces);
1058 const int ChangeMinColumn =
C.StartOfTokenColumn;
1059 int ChangeMaxColumn;
1063 if (!
C.CreateReplacement)
1064 ChangeMaxColumn = ChangeMinColumn;
1065 else if (Style.ColumnLimit == 0)
1067 else if (Style.ColumnLimit >=
C.TokenLength)
1068 ChangeMaxColumn = Style.ColumnLimit -
C.TokenLength;
1070 ChangeMaxColumn = ChangeMinColumn;
1072 if (I + 1 < Size && Changes[I + 1].ContinuesPPDirective &&
1073 ChangeMaxColumn >= 2) {
1074 ChangeMaxColumn -= 2;
1077 bool WasAlignedWithStartOfNextLine =
false;
1078 if (
C.NewlinesBefore >= 1) {
1079 const auto CommentColumn =
1080 SourceMgr.getSpellingColumnNumber(
C.OriginalWhitespaceRange.getEnd());
1081 for (
int J = I + 1; J <
Size; ++J) {
1082 if (Changes[J].
Tok->is(tok::comment))
1086 C.AlignedTo =
C.Tok->getPrevious(tok::comment);
1087 const auto NextColumn = SourceMgr.getSpellingColumnNumber(
1088 Changes[J].OriginalWhitespaceRange.getEnd());
1091 WasAlignedWithStartOfNextLine =
1092 CommentColumn == NextColumn ||
1093 CommentColumn == NextColumn + Style.IndentWidth;
1100 auto DontAlignThisComment = [](
const auto *
Tok) {
1101 if (
Tok->is(tok::semi)) {
1102 Tok =
Tok->getPreviousNonComment();
1106 if (
Tok->is(tok::r_paren)) {
1108 Tok =
Tok->MatchingParen;
1111 Tok =
Tok->getPreviousNonComment();
1114 if (
Tok->is(TT_DoWhile)) {
1115 const auto *Prev =
Tok->getPreviousNonComment();
1124 if (
Tok->isNot(tok::r_brace))
1127 while (
Tok->Previous &&
Tok->Previous->is(tok::r_brace))
1129 return Tok->NewlinesBefore > 0;
1132 if (I > 0 &&
C.NewlinesBefore == 0 &&
1133 DontAlignThisComment(Changes[I - 1].
Tok)) {
1134 alignTrailingComments(StartOfSequence, I, MinColumn);
1139 StartOfSequence = I + 1;
1140 }
else if (BreakBeforeNext ||
Newlines > NewLineThreshold ||
1141 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1144 (
C.NewlinesBefore == 1 && I > 0 &&
1145 !Changes[I - 1].IsTrailingComment) ||
1146 WasAlignedWithStartOfNextLine) {
1147 alignTrailingComments(StartOfSequence, I, MinColumn);
1148 MinColumn = ChangeMinColumn;
1149 MaxColumn = ChangeMaxColumn;
1150 StartOfSequence = I;
1152 MinColumn = std::max(MinColumn, ChangeMinColumn);
1153 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1155 BreakBeforeNext = (I == 0) || (
C.NewlinesBefore > 1) ||
1158 (
C.NewlinesBefore == 1 && StartOfSequence == I);
1161 alignTrailingComments(StartOfSequence, Size, MinColumn);
1164void WhitespaceManager::alignTrailingComments(
unsigned Start,
unsigned End,
1166 for (
unsigned i = Start; i != End; ++i) {
1168 if (Changes[i].IsTrailingComment)
1170 if (Changes[i].StartOfBlockComment) {
1171 Shift = Changes[i].IndentationOffset +
1172 Changes[i].StartOfBlockComment->StartOfTokenColumn -
1173 Changes[i].StartOfTokenColumn;
1178 setChangeSpaces(i, Changes[i].Spaces + Shift);
1182void WhitespaceManager::alignEscapedNewlines() {
1183 const auto Align = Style.AlignEscapedNewlines;
1184 if (Align == FormatStyle::ENAS_DontAlign)
1187 const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
1188 const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
1189 const auto MaxColumn = Style.ColumnLimit;
1190 unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1191 unsigned StartOfMacro = 0;
1192 for (
unsigned i = 1, e = Changes.size(); i < e; ++i) {
1194 if (
C.NewlinesBefore == 0 && (!WithLastLine ||
C.Tok->isNot(tok::eof)))
1197 const auto BackslashColumn =
C.PreviousEndOfTokenColumn + 2;
1198 if (InPPDirective ||
1199 (WithLastLine && (MaxColumn == 0 || BackslashColumn <= MaxColumn))) {
1200 MaxEndOfLine = std::max(BackslashColumn, MaxEndOfLine);
1202 if (!InPPDirective) {
1203 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1204 MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1208 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1211void WhitespaceManager::alignEscapedNewlines(
unsigned Start,
unsigned End,
1213 for (
unsigned i = Start; i < End; ++i) {
1215 if (
C.NewlinesBefore > 0) {
1216 assert(
C.ContinuesPPDirective);
1217 if (
C.PreviousEndOfTokenColumn + 1 >
Column)
1218 C.EscapedNewlineColumn = 0;
1220 C.EscapedNewlineColumn =
Column;
1225void WhitespaceManager::alignArrayInitializers() {
1226 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1229 for (
unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1230 ChangeIndex < ChangeEnd; ++ChangeIndex) {
1231 auto &
C = Changes[ChangeIndex];
1232 if (
C.Tok->IsArrayInitializer) {
1233 bool FoundComplete =
false;
1234 for (
unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1236 const auto *
Tok = Changes[InsideIndex].Tok;
1237 if (
Tok->is(tok::pp_define))
1239 if (
Tok ==
C.Tok->MatchingParen) {
1240 alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1241 ChangeIndex = InsideIndex + 1;
1242 FoundComplete =
true;
1247 ChangeIndex = ChangeEnd;
1252void WhitespaceManager::alignArrayInitializers(
unsigned Start,
unsigned End) {
1254 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1255 alignArrayInitializersRightJustified(getCells(Start, End));
1256 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1257 alignArrayInitializersLeftJustified(getCells(Start, End));
1260void WhitespaceManager::alignArrayInitializersRightJustified(
1261 CellDescriptions &&CellDescs) {
1262 if (!CellDescs.isRectangular())
1265 const int BracePadding =
1266 Style.Cpp11BracedListStyle != FormatStyle::BLS_Block ? 0 : 1;
1267 auto &Cells = CellDescs.Cells;
1269 auto *CellIter = Cells.begin();
1270 for (
auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1271 unsigned NetWidth = 0U;
1272 if (isSplitCell(*CellIter))
1273 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1274 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1276 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1280 const auto *
Next = CellIter;
1284 Changes[
Next->Index].NewlinesBefore = 0;
1285 setChangeSpaces(
Next->Index, BracePadding);
1291 if (CellIter != Cells.begin()) {
1293 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1294 auto MaxNetWidth = getMaximumNetWidth(
1295 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1296 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1297 if (ThisNetWidth < MaxNetWidth)
1298 setChangeSpaces(CellIter->Index, MaxNetWidth - ThisNetWidth);
1300 auto Offset = std::distance(Cells.begin(), CellIter);
1301 for (
const auto *
Next = CellIter->NextColumnElement;
Next;
1303 if (RowCount >= CellDescs.CellCounts.size())
1305 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1306 auto *End = Start + Offset;
1307 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1308 if (ThisNetWidth < MaxNetWidth)
1309 setChangeSpaces(
Next->Index, MaxNetWidth - ThisNetWidth);
1315 calculateCellWidth(CellIter->Index, CellIter->EndIndex,
true) +
1317 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1318 int Spaces = (CellWidth - (ThisWidth + NetWidth));
1319 Spaces += (i > 0) ? 1 : BracePadding;
1321 setChangeSpaces(CellIter->Index, Spaces);
1323 alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1324 for (
const auto *
Next = CellIter->NextColumnElement;
Next;
1327 calculateCellWidth(
Next->Index,
Next->EndIndex,
true) + NetWidth;
1328 if (Changes[
Next->Index].NewlinesBefore == 0) {
1329 int Spaces = (CellWidth - ThisWidth);
1330 Spaces += (i > 0) ? 1 : BracePadding;
1332 setChangeSpaces(
Next->Index, Spaces);
1334 alignToStartOfCell(
Next->Index,
Next->EndIndex);
1340void WhitespaceManager::alignArrayInitializersLeftJustified(
1341 CellDescriptions &&CellDescs) {
1343 if (!CellDescs.isRectangular())
1346 const int BracePadding =
1347 Style.Cpp11BracedListStyle != FormatStyle::BLS_Block ? 0 : 1;
1348 auto &Cells = CellDescs.Cells;
1350 auto *CellIter = Cells.begin();
1356 setChangeSpaces(
Next->Index, Spaces);
1359 for (
auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1360 auto MaxNetWidth = getMaximumNetWidth(
1361 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1362 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1364 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1365 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1367 MaxNetWidth - ThisNetWidth +
1368 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1
1370 setChangeSpaces(CellIter->Index, Spaces);
1373 auto Offset = std::distance(Cells.begin(), CellIter);
1374 for (
const auto *
Next = CellIter->NextColumnElement;
Next;
1376 if (RowCount >= CellDescs.CellCounts.size())
1378 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1379 auto *End = Start + Offset;
1380 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1381 if (Changes[
Next->Index].NewlinesBefore == 0) {
1383 MaxNetWidth - ThisNetWidth +
1384 (Changes[
Next->Index].Tok->isNot(tok::r_brace) ? 1 : BracePadding);
1385 setChangeSpaces(
Next->Index, Spaces);
1392bool WhitespaceManager::isSplitCell(
const CellDescription &Cell) {
1395 for (
const auto *
Next = Cell.NextColumnElement;
Next;
1403WhitespaceManager::CellDescriptions WhitespaceManager::getCells(
unsigned Start,
1408 SmallVector<unsigned> CellCounts;
1409 unsigned InitialSpaces = 0;
1410 unsigned InitialTokenLength = 0;
1411 unsigned EndSpaces = 0;
1412 SmallVector<CellDescription> Cells;
1414 for (
unsigned i = Start; i < End; ++i) {
1415 auto &
C = Changes[i];
1416 if (
C.Tok->is(tok::l_brace))
1418 else if (
C.Tok->is(tok::r_brace))
1421 if (
C.Tok->is(tok::l_brace)) {
1424 if (InitialSpaces == 0) {
1425 InitialSpaces =
C.Spaces +
C.TokenLength;
1426 InitialTokenLength =
C.TokenLength;
1428 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1429 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1430 InitialTokenLength += Changes[j].TokenLength;
1432 if (
C.NewlinesBefore == 0) {
1433 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1434 InitialTokenLength += Changes[j].TokenLength;
1437 }
else if (
C.Tok->is(tok::comma)) {
1439 Cells.back().EndIndex = i;
1440 if (
const auto *
Next =
C.Tok->getNextNonComment();
1441 Next &&
Next->isNot(tok::r_brace)) {
1445 }
else if (Depth == 1) {
1448 Cells.back().EndIndex = i;
1449 Cells.push_back(CellDescription{i, ++Cell, i + 1,
false,
nullptr});
1450 CellCounts.push_back(
C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1453 const auto *NextNonComment =
C.Tok->getNextNonComment();
1454 while (NextNonComment && NextNonComment->is(tok::comma))
1455 NextNonComment = NextNonComment->getNextNonComment();
1457 while (j < End && Changes[j].
Tok != NextNonComment)
1460 Changes[j].
Tok->isNot(tok::r_brace)) {
1461 Changes[j].NewlinesBefore = 1;
1463 setChangeSpaces(j, InitialSpaces - InitialTokenLength);
1465 }
else if (
C.Tok->is(tok::comment) &&
C.Tok->NewlinesBefore == 0) {
1467 setChangeSpaces(i, Changes[i - 1].
Tok->is(tok::comma) ? 1 : 2);
1468 }
else if (
C.Tok->is(tok::l_brace)) {
1472 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1474 EndSpaces = Changes[j].Spaces;
1476 }
else if (Depth == 0 &&
C.Tok->is(tok::r_brace)) {
1477 C.NewlinesBefore = 1;
1478 setChangeSpaces(i, EndSpaces);
1480 if (
C.Tok->StartsColumn) {
1483 bool HasSplit =
false;
1500 if ((j - 1) > Start && Changes[j].
Tok->is(tok::comma) &&
1501 Changes[j - 1].NewlinesBefore > 0) {
1503 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1504 if (LineLimit < Style.ColumnLimit) {
1505 Changes[i].NewlinesBefore = 0;
1506 setChangeSpaces(i, 1);
1511 setChangeSpaces(i, InitialSpaces);
1515 if (Changes[i].
Tok !=
C.Tok)
1517 Cells.push_back(CellDescription{i, Cell, i, HasSplit,
nullptr});
1521 return linkCells({Cells, CellCounts, InitialSpaces});
1524unsigned WhitespaceManager::calculateCellWidth(
unsigned Start,
unsigned End,
1525 bool WithSpaces)
const {
1526 unsigned CellWidth = 0;
1527 for (
auto i = Start; i < End; i++) {
1530 CellWidth += Changes[i].TokenLength;
1531 CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1536void WhitespaceManager::alignToStartOfCell(
unsigned Start,
unsigned End) {
1537 if ((End - Start) <= 1)
1541 for (
auto i = Start + 1; i < End; i++)
1543 setChangeSpaces(i, Changes[Start].Spaces);
1546WhitespaceManager::CellDescriptions
1547WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1548 auto &Cells = CellDesc.Cells;
1549 for (
auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1550 if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1551 for (
auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1552 if (NextIter->Cell == CellIter->Cell) {
1553 CellIter->NextColumnElement = &(*NextIter);
1559 return std::move(CellDesc);
1562void WhitespaceManager::setChangeSpaces(
unsigned Start,
unsigned Spaces) {
1566void WhitespaceManager::generateChanges() {
1567 for (
unsigned i = 0, e = Changes.size(); i != e; ++i) {
1570 auto Last = Changes[i - 1].OriginalWhitespaceRange;
1571 auto New = Changes[i].OriginalWhitespaceRange;
1613 if (
Last.getBegin() ==
New.getBegin() &&
1614 (
Last.getEnd() !=
Last.getBegin() ||
1615 New.getEnd() ==
New.getBegin())) {
1619 if (
C.CreateReplacement) {
1620 std::string ReplacementText =
C.PreviousLinePostfix;
1621 if (
C.ContinuesPPDirective) {
1622 appendEscapedNewlineText(ReplacementText,
C.NewlinesBefore,
1623 C.PreviousEndOfTokenColumn,
1624 C.EscapedNewlineColumn);
1626 appendNewlineText(ReplacementText,
C);
1631 appendIndentText(ReplacementText,
IndentLevel, std::max(0,
C.Spaces),
1632 std::max((
int)
C.StartOfTokenColumn,
C.Spaces) -
1633 std::max(0,
C.Spaces),
1635 C.Tok->AppliedIndentLevel =
1636 C.AlignedTo ?
IndentLevel : std::max(0,
C.Spaces) / Style.IndentWidth;
1637 ReplacementText.append(
C.CurrentLinePrefix);
1638 storeReplacement(
C.OriginalWhitespaceRange, ReplacementText);
1643void WhitespaceManager::storeReplacement(SourceRange Range, StringRef
Text) {
1644 unsigned WhitespaceLength = SourceMgr.getFileOffset(
Range.getEnd()) -
1645 SourceMgr.getFileOffset(
Range.getBegin());
1647 if (StringRef(SourceMgr.getCharacterData(
Range.getBegin()),
1648 WhitespaceLength) ==
Text) {
1651 auto Err = Replaces.add(tooling::Replacement(
1656 llvm::errs() << llvm::toString(std::move(Err)) <<
"\n";
1661void WhitespaceManager::appendNewlineText(std::string &
Text,
const Change &
C) {
1662 if (
C.NewlinesBefore <= 0)
1665 StringRef Newline = UseCRLF ?
"\r\n" :
"\n";
1666 Text.append(Newline);
1668 if (
C.Tok->HasFormFeedBefore)
1671 for (
unsigned I = 1; I <
C.NewlinesBefore; ++I)
1672 Text.append(Newline);
1675void WhitespaceManager::appendEscapedNewlineText(
1676 std::string &
Text,
unsigned Newlines,
unsigned PreviousEndOfTokenColumn,
1677 unsigned EscapedNewlineColumn) {
1680 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1681 for (
unsigned i = 0; i <
Newlines; ++i) {
1682 Text.append(Spaces,
' ');
1683 Text.append(UseCRLF ?
"\\\r\n" :
"\\\n");
1684 Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1689void WhitespaceManager::appendIndentText(std::string &
Text,
1691 unsigned WhitespaceStartColumn,
1693 switch (Style.UseTab) {
1694 case FormatStyle::UT_Never:
1695 Text.append(Spaces,
' ');
1697 case FormatStyle::UT_Always: {
1698 if (Style.TabWidth) {
1699 unsigned FirstTabWidth =
1700 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1703 if (Spaces < FirstTabWidth || Spaces == 1) {
1704 Text.append(Spaces,
' ');
1708 Spaces -= FirstTabWidth;
1711 Text.append(Spaces / Style.TabWidth,
'\t');
1712 Text.append(Spaces % Style.TabWidth,
' ');
1713 }
else if (Spaces == 1) {
1714 Text.append(Spaces,
' ');
1718 case FormatStyle::UT_ForIndentation:
1719 if (WhitespaceStartColumn == 0) {
1720 unsigned Indentation =
IndentLevel * Style.IndentWidth;
1721 Spaces = appendTabIndent(
Text, Spaces, Indentation);
1723 Text.append(Spaces,
' ');
1725 case FormatStyle::UT_ForContinuationAndIndentation:
1726 if (WhitespaceStartColumn == 0)
1727 Spaces = appendTabIndent(
Text, Spaces, Spaces);
1728 Text.append(Spaces,
' ');
1730 case FormatStyle::UT_AlignWithSpaces:
1731 if (WhitespaceStartColumn == 0) {
1732 unsigned Indentation =
1733 IsAligned ?
IndentLevel * Style.IndentWidth : Spaces;
1734 Spaces = appendTabIndent(
Text, Spaces, Indentation);
1736 Text.append(Spaces,
' ');
1741unsigned WhitespaceManager::appendTabIndent(std::string &
Text,
unsigned Spaces,
1742 unsigned Indentation) {
1745 if (Indentation > Spaces)
1746 Indentation = Spaces;
1747 if (Style.TabWidth) {
1748 unsigned Tabs = Indentation / Style.TabWidth;
1749 Text.append(Tabs,
'\t');
1750 Spaces -= Tabs * Style.TabWidth;
WhitespaceManager class manages whitespace around tokens and their replacements.
__DEVICE__ long long abs(long long __n)
static CharSourceRange getCharRange(SourceRange R)
Encodes a location in the source.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
The JSON file list parser is used to communicate input to InstallAPI.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
@ Type
The name was classified as a type.