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 (NewLineThreshold > 1 &&
C.Tok->is(
BK_Block)) {
1037 alignTrailingComments(StartOfSequence, I, MinColumn);
1040 StartOfSequence = I + 1;
1044 if (!
C.IsTrailingComment)
1047 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1048 const int OriginalSpaces =
1049 C.OriginalWhitespaceRange.getEnd().getRawEncoding() -
1050 C.OriginalWhitespaceRange.getBegin().getRawEncoding() -
1051 C.Tok->LastNewlineOffset;
1052 assert(OriginalSpaces >= 0);
1053 const auto RestoredLineLength =
1054 C.StartOfTokenColumn +
C.TokenLength + OriginalSpaces;
1057 if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit > 0)
1061 C.NewlinesBefore > 0 ?
C.Tok->OriginalColumn : OriginalSpaces;
1062 setChangeSpaces(I, Spaces);
1066 const int ChangeMinColumn =
C.StartOfTokenColumn;
1067 int ChangeMaxColumn;
1071 if (!
C.CreateReplacement)
1072 ChangeMaxColumn = ChangeMinColumn;
1073 else if (Style.ColumnLimit == 0)
1075 else if (Style.ColumnLimit >=
C.TokenLength)
1076 ChangeMaxColumn = Style.ColumnLimit -
C.TokenLength;
1078 ChangeMaxColumn = ChangeMinColumn;
1080 if (I + 1 < Size && Changes[I + 1].ContinuesPPDirective &&
1081 ChangeMaxColumn >= 2) {
1082 ChangeMaxColumn -= 2;
1085 bool WasAlignedWithStartOfNextLine =
false;
1086 if (
C.NewlinesBefore >= 1) {
1087 const auto CommentColumn =
1088 SourceMgr.getSpellingColumnNumber(
C.OriginalWhitespaceRange.getEnd());
1089 for (
int J = I + 1; J <
Size; ++J) {
1090 if (Changes[J].
Tok->is(tok::comment))
1094 C.AlignedTo =
C.Tok->getPrevious(tok::comment);
1095 const auto NextColumn = SourceMgr.getSpellingColumnNumber(
1096 Changes[J].OriginalWhitespaceRange.getEnd());
1099 WasAlignedWithStartOfNextLine =
1100 CommentColumn == NextColumn ||
1101 CommentColumn == NextColumn + Style.IndentWidth;
1108 auto DontAlignThisComment = [](
const auto *
Tok) {
1109 if (
Tok->is(tok::semi)) {
1110 Tok =
Tok->getPreviousNonComment();
1114 if (
Tok->is(tok::r_paren)) {
1116 Tok =
Tok->MatchingParen;
1119 Tok =
Tok->getPreviousNonComment();
1122 if (
Tok->is(TT_DoWhile)) {
1123 const auto *Prev =
Tok->getPreviousNonComment();
1132 if (
Tok->isNot(tok::r_brace))
1135 while (
Tok->Previous &&
Tok->Previous->is(tok::r_brace))
1137 return Tok->NewlinesBefore > 0;
1140 if (I > 0 &&
C.NewlinesBefore == 0 &&
1141 DontAlignThisComment(Changes[I - 1].
Tok)) {
1142 alignTrailingComments(StartOfSequence, I, MinColumn);
1147 StartOfSequence = I + 1;
1148 }
else if (BreakBeforeNext ||
Newlines > NewLineThreshold ||
1149 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1152 (
C.NewlinesBefore == 1 && I > 0 &&
1153 !Changes[I - 1].IsTrailingComment) ||
1154 WasAlignedWithStartOfNextLine) {
1155 alignTrailingComments(StartOfSequence, I, MinColumn);
1156 MinColumn = ChangeMinColumn;
1157 MaxColumn = ChangeMaxColumn;
1158 StartOfSequence = I;
1160 MinColumn = std::max(MinColumn, ChangeMinColumn);
1161 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1163 BreakBeforeNext = (I == 0) || (
C.NewlinesBefore > 1) ||
1166 (
C.NewlinesBefore == 1 && StartOfSequence == I);
1169 alignTrailingComments(StartOfSequence, Size, MinColumn);
1172void WhitespaceManager::alignTrailingComments(
unsigned Start,
unsigned End,
1174 for (
unsigned i = Start; i != End; ++i) {
1176 if (Changes[i].IsTrailingComment)
1178 if (Changes[i].StartOfBlockComment) {
1179 Shift = Changes[i].IndentationOffset +
1180 Changes[i].StartOfBlockComment->StartOfTokenColumn -
1181 Changes[i].StartOfTokenColumn;
1186 setChangeSpaces(i, Changes[i].Spaces + Shift);
1190void WhitespaceManager::alignEscapedNewlines() {
1191 const auto Align = Style.AlignEscapedNewlines;
1192 if (Align == FormatStyle::ENAS_DontAlign)
1195 const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
1196 const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
1197 const auto MaxColumn = Style.ColumnLimit;
1198 unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1199 unsigned StartOfMacro = 0;
1200 for (
unsigned i = 1, e = Changes.size(); i < e; ++i) {
1202 if (
C.NewlinesBefore == 0 && (!WithLastLine ||
C.Tok->isNot(tok::eof)))
1205 const auto BackslashColumn =
C.PreviousEndOfTokenColumn + 2;
1206 if (InPPDirective ||
1207 (WithLastLine && (MaxColumn == 0 || BackslashColumn <= MaxColumn))) {
1208 MaxEndOfLine = std::max(BackslashColumn, MaxEndOfLine);
1210 if (!InPPDirective) {
1211 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1212 MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1216 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1219void WhitespaceManager::alignEscapedNewlines(
unsigned Start,
unsigned End,
1221 for (
unsigned i = Start; i < End; ++i) {
1223 if (
C.NewlinesBefore > 0) {
1224 assert(
C.ContinuesPPDirective);
1225 if (
C.PreviousEndOfTokenColumn + 1 >
Column)
1226 C.EscapedNewlineColumn = 0;
1228 C.EscapedNewlineColumn =
Column;
1233void WhitespaceManager::alignArrayInitializers() {
1234 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1237 for (
unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1238 ChangeIndex < ChangeEnd; ++ChangeIndex) {
1239 auto &
C = Changes[ChangeIndex];
1240 if (
C.Tok->IsArrayInitializer) {
1241 bool FoundComplete =
false;
1242 for (
unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1244 const auto *
Tok = Changes[InsideIndex].Tok;
1245 if (
Tok->is(tok::pp_define))
1247 if (
Tok ==
C.Tok->MatchingParen) {
1248 alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1249 ChangeIndex = InsideIndex + 1;
1250 FoundComplete =
true;
1255 ChangeIndex = ChangeEnd;
1260void WhitespaceManager::alignArrayInitializers(
unsigned Start,
unsigned End) {
1262 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1263 alignArrayInitializersRightJustified(getCells(Start, End));
1264 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1265 alignArrayInitializersLeftJustified(getCells(Start, End));
1268void WhitespaceManager::alignArrayInitializersRightJustified(
1269 CellDescriptions &&CellDescs) {
1270 if (!CellDescs.isRectangular())
1273 const int BracePadding =
1274 Style.Cpp11BracedListStyle != FormatStyle::BLS_Block ? 0 : 1;
1275 auto &Cells = CellDescs.Cells;
1277 auto *CellIter = Cells.begin();
1278 for (
auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1279 unsigned NetWidth = 0U;
1280 if (isSplitCell(*CellIter))
1281 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1282 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1284 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1288 const auto *
Next = CellIter;
1292 Changes[
Next->Index].NewlinesBefore = 0;
1293 setChangeSpaces(
Next->Index, BracePadding);
1299 if (CellIter != Cells.begin()) {
1301 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1302 auto MaxNetWidth = getMaximumNetWidth(
1303 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1304 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1305 if (ThisNetWidth < MaxNetWidth)
1306 setChangeSpaces(CellIter->Index, MaxNetWidth - ThisNetWidth);
1308 auto Offset = std::distance(Cells.begin(), CellIter);
1309 for (
const auto *
Next = CellIter->NextColumnElement;
Next;
1311 if (RowCount >= CellDescs.CellCounts.size())
1313 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1314 auto *End = Start + Offset;
1315 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1316 if (ThisNetWidth < MaxNetWidth)
1317 setChangeSpaces(
Next->Index, MaxNetWidth - ThisNetWidth);
1323 calculateCellWidth(CellIter->Index, CellIter->EndIndex,
true) +
1325 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1326 int Spaces = (CellWidth - (ThisWidth + NetWidth));
1327 Spaces += (i > 0) ? 1 : BracePadding;
1329 setChangeSpaces(CellIter->Index, Spaces);
1331 alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1332 for (
const auto *
Next = CellIter->NextColumnElement;
Next;
1335 calculateCellWidth(
Next->Index,
Next->EndIndex,
true) + NetWidth;
1336 if (Changes[
Next->Index].NewlinesBefore == 0) {
1337 int Spaces = (CellWidth - ThisWidth);
1338 Spaces += (i > 0) ? 1 : BracePadding;
1340 setChangeSpaces(
Next->Index, Spaces);
1342 alignToStartOfCell(
Next->Index,
Next->EndIndex);
1348void WhitespaceManager::alignArrayInitializersLeftJustified(
1349 CellDescriptions &&CellDescs) {
1351 if (!CellDescs.isRectangular())
1354 const int BracePadding =
1355 Style.Cpp11BracedListStyle != FormatStyle::BLS_Block ? 0 : 1;
1356 auto &Cells = CellDescs.Cells;
1358 auto *CellIter = Cells.begin();
1364 setChangeSpaces(
Next->Index, Spaces);
1367 for (
auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1368 auto MaxNetWidth = getMaximumNetWidth(
1369 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1370 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1372 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1373 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1375 MaxNetWidth - ThisNetWidth +
1376 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1
1378 setChangeSpaces(CellIter->Index, Spaces);
1381 auto Offset = std::distance(Cells.begin(), CellIter);
1382 for (
const auto *
Next = CellIter->NextColumnElement;
Next;
1384 if (RowCount >= CellDescs.CellCounts.size())
1386 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1387 auto *End = Start + Offset;
1388 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1389 if (Changes[
Next->Index].NewlinesBefore == 0) {
1391 MaxNetWidth - ThisNetWidth +
1392 (Changes[
Next->Index].Tok->isNot(tok::r_brace) ? 1 : BracePadding);
1393 setChangeSpaces(
Next->Index, Spaces);
1400bool WhitespaceManager::isSplitCell(
const CellDescription &Cell) {
1403 for (
const auto *
Next = Cell.NextColumnElement;
Next;
1411WhitespaceManager::CellDescriptions WhitespaceManager::getCells(
unsigned Start,
1416 SmallVector<unsigned> CellCounts;
1417 unsigned InitialSpaces = 0;
1418 unsigned InitialTokenLength = 0;
1419 unsigned EndSpaces = 0;
1420 SmallVector<CellDescription> Cells;
1422 for (
unsigned i = Start; i < End; ++i) {
1423 auto &
C = Changes[i];
1424 if (
C.Tok->is(tok::l_brace))
1426 else if (
C.Tok->is(tok::r_brace))
1429 if (
C.Tok->is(tok::l_brace)) {
1432 if (InitialSpaces == 0) {
1433 InitialSpaces =
C.Spaces +
C.TokenLength;
1434 InitialTokenLength =
C.TokenLength;
1436 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1437 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1438 InitialTokenLength += Changes[j].TokenLength;
1440 if (
C.NewlinesBefore == 0) {
1441 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1442 InitialTokenLength += Changes[j].TokenLength;
1445 }
else if (
C.Tok->is(tok::comma)) {
1447 Cells.back().EndIndex = i;
1448 if (
const auto *
Next =
C.Tok->getNextNonComment();
1449 Next &&
Next->isNot(tok::r_brace)) {
1453 }
else if (Depth == 1) {
1456 Cells.back().EndIndex = i;
1457 Cells.push_back(CellDescription{i, ++Cell, i + 1,
false,
nullptr});
1458 CellCounts.push_back(
C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1461 const auto *NextNonComment =
C.Tok->getNextNonComment();
1462 while (NextNonComment && NextNonComment->is(tok::comma))
1463 NextNonComment = NextNonComment->getNextNonComment();
1465 while (j < End && Changes[j].
Tok != NextNonComment)
1468 Changes[j].
Tok->isNot(tok::r_brace)) {
1469 Changes[j].NewlinesBefore = 1;
1471 setChangeSpaces(j, InitialSpaces - InitialTokenLength);
1473 }
else if (
C.Tok->is(tok::comment) &&
C.Tok->NewlinesBefore == 0) {
1475 setChangeSpaces(i, Changes[i - 1].
Tok->is(tok::comma) ? 1 : 2);
1476 }
else if (
C.Tok->is(tok::l_brace)) {
1480 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1482 EndSpaces = Changes[j].Spaces;
1484 }
else if (Depth == 0 &&
C.Tok->is(tok::r_brace)) {
1485 C.NewlinesBefore = 1;
1486 setChangeSpaces(i, EndSpaces);
1488 if (
C.Tok->StartsColumn) {
1491 bool HasSplit =
false;
1508 if ((j - 1) > Start && Changes[j].
Tok->is(tok::comma) &&
1509 Changes[j - 1].NewlinesBefore > 0) {
1511 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1512 if (LineLimit < Style.ColumnLimit) {
1513 Changes[i].NewlinesBefore = 0;
1514 setChangeSpaces(i, 1);
1519 setChangeSpaces(i, InitialSpaces);
1523 if (Changes[i].
Tok !=
C.Tok)
1525 Cells.push_back(CellDescription{i, Cell, i, HasSplit,
nullptr});
1529 return linkCells({Cells, CellCounts, InitialSpaces});
1532unsigned WhitespaceManager::calculateCellWidth(
unsigned Start,
unsigned End,
1533 bool WithSpaces)
const {
1534 unsigned CellWidth = 0;
1535 for (
auto i = Start; i < End; i++) {
1538 CellWidth += Changes[i].TokenLength;
1539 CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1544void WhitespaceManager::alignToStartOfCell(
unsigned Start,
unsigned End) {
1545 if ((End - Start) <= 1)
1549 for (
auto i = Start + 1; i < End; i++)
1551 setChangeSpaces(i, Changes[Start].Spaces);
1554WhitespaceManager::CellDescriptions
1555WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1556 auto &Cells = CellDesc.Cells;
1557 for (
auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1558 if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1559 for (
auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1560 if (NextIter->Cell == CellIter->Cell) {
1561 CellIter->NextColumnElement = &(*NextIter);
1567 return std::move(CellDesc);
1570void WhitespaceManager::setChangeSpaces(
unsigned Start,
unsigned Spaces) {
1574void WhitespaceManager::generateChanges() {
1575 for (
unsigned i = 0, e = Changes.size(); i != e; ++i) {
1578 auto Last = Changes[i - 1].OriginalWhitespaceRange;
1579 auto New = Changes[i].OriginalWhitespaceRange;
1621 if (
Last.getBegin() ==
New.getBegin() &&
1622 (
Last.getEnd() !=
Last.getBegin() ||
1623 New.getEnd() ==
New.getBegin())) {
1627 if (
C.CreateReplacement) {
1628 std::string ReplacementText =
C.PreviousLinePostfix;
1629 if (
C.ContinuesPPDirective) {
1630 appendEscapedNewlineText(ReplacementText,
C.NewlinesBefore,
1631 C.PreviousEndOfTokenColumn,
1632 C.EscapedNewlineColumn);
1634 appendNewlineText(ReplacementText,
C);
1639 appendIndentText(ReplacementText,
IndentLevel, std::max(0,
C.Spaces),
1640 std::max((
int)
C.StartOfTokenColumn,
C.Spaces) -
1641 std::max(0,
C.Spaces),
1643 C.Tok->AppliedIndentLevel =
1644 C.AlignedTo ?
IndentLevel : std::max(0,
C.Spaces) / Style.IndentWidth;
1645 ReplacementText.append(
C.CurrentLinePrefix);
1646 storeReplacement(
C.OriginalWhitespaceRange, ReplacementText);
1651void WhitespaceManager::storeReplacement(SourceRange Range, StringRef
Text) {
1652 unsigned WhitespaceLength = SourceMgr.getFileOffset(
Range.getEnd()) -
1653 SourceMgr.getFileOffset(
Range.getBegin());
1655 if (StringRef(SourceMgr.getCharacterData(
Range.getBegin()),
1656 WhitespaceLength) ==
Text) {
1659 auto Err = Replaces.add(tooling::Replacement(
1664 llvm::errs() << llvm::toString(std::move(Err)) <<
"\n";
1669void WhitespaceManager::appendNewlineText(std::string &
Text,
const Change &
C) {
1670 if (
C.NewlinesBefore <= 0)
1673 StringRef Newline = UseCRLF ?
"\r\n" :
"\n";
1674 Text.append(Newline);
1676 if (
C.Tok->HasFormFeedBefore)
1679 for (
unsigned I = 1; I <
C.NewlinesBefore; ++I)
1680 Text.append(Newline);
1683void WhitespaceManager::appendEscapedNewlineText(
1684 std::string &
Text,
unsigned Newlines,
unsigned PreviousEndOfTokenColumn,
1685 unsigned EscapedNewlineColumn) {
1688 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1689 for (
unsigned i = 0; i <
Newlines; ++i) {
1690 Text.append(Spaces,
' ');
1691 Text.append(UseCRLF ?
"\\\r\n" :
"\\\n");
1692 Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1697void WhitespaceManager::appendIndentText(std::string &
Text,
1699 unsigned WhitespaceStartColumn,
1701 switch (Style.UseTab) {
1702 case FormatStyle::UT_Never:
1703 Text.append(Spaces,
' ');
1705 case FormatStyle::UT_Always: {
1706 if (Style.TabWidth) {
1707 unsigned FirstTabWidth =
1708 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1711 if (Spaces < FirstTabWidth || Spaces == 1) {
1712 Text.append(Spaces,
' ');
1716 Spaces -= FirstTabWidth;
1719 Text.append(Spaces / Style.TabWidth,
'\t');
1720 Text.append(Spaces % Style.TabWidth,
' ');
1721 }
else if (Spaces == 1) {
1722 Text.append(Spaces,
' ');
1726 case FormatStyle::UT_ForIndentation:
1727 if (WhitespaceStartColumn == 0) {
1728 unsigned Indentation =
IndentLevel * Style.IndentWidth;
1729 Spaces = appendTabIndent(
Text, Spaces, Indentation);
1731 Text.append(Spaces,
' ');
1733 case FormatStyle::UT_ForContinuationAndIndentation:
1734 if (WhitespaceStartColumn == 0)
1735 Spaces = appendTabIndent(
Text, Spaces, Spaces);
1736 Text.append(Spaces,
' ');
1738 case FormatStyle::UT_AlignWithSpaces:
1739 if (WhitespaceStartColumn == 0) {
1740 unsigned Indentation =
1741 IsAligned ?
IndentLevel * Style.IndentWidth : Spaces;
1742 Spaces = appendTabIndent(
Text, Spaces, Indentation);
1744 Text.append(Spaces,
' ');
1749unsigned WhitespaceManager::appendTabIndent(std::string &
Text,
unsigned Spaces,
1750 unsigned Indentation) {
1753 if (Indentation > Spaces)
1754 Indentation = Spaces;
1755 if (Style.TabWidth) {
1756 unsigned Tabs = Indentation / Style.TabWidth;
1757 Text.append(Tabs,
'\t');
1758 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.