clang 24.0.0git
WhitespaceManager.cpp
Go to the documentation of this file.
1//===--- WhitespaceManager.cpp - Format C++ code --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements WhitespaceManager class.
11///
12//===----------------------------------------------------------------------===//
13
14#include "WhitespaceManager.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallVector.h"
17#include <algorithm>
18#include <limits>
19#include <optional>
20
21namespace clang {
22namespace format {
23
24static const FormatToken &getLineStart(const FormatToken &Tok) {
25 const FormatToken *Result = &Tok;
26 while (Result->getDecision() != FormatDecision::FD_Break && Result->Previous)
27 Result = Result->Previous;
28 return *Result;
29}
30
32 if (!C.AlignedTo)
33 return C.Tok->IndentLevel;
34
35 const FormatToken &LineStart = getLineStart(*C.AlignedTo);
36 return std::max(LineStart.IndentLevel, LineStart.AppliedIndentLevel);
37}
38
40 const Change &C1, const Change &C2) const {
41 return SourceMgr.isBeforeInTranslationUnit(
46 SourceMgr.isBeforeInTranslationUnit(
49}
50
69
71 FormatToken &Tok, unsigned Newlines, unsigned Spaces,
72 unsigned StartOfTokenColumn, const FormatToken *AlignedTo,
73 bool InPPDirective, unsigned IndentedFromColumn, bool CreateReplacement) {
74 if (Tok.Finalized || (Tok.MacroCtx && Tok.MacroCtx->Role == MR_ExpandedArg))
75 return;
76 if (CreateReplacement)
77 Tok.setDecision((Newlines > 0) ? FD_Break : FD_Continue);
78 Changes.push_back(Change(Tok, CreateReplacement, Tok.WhitespaceRange, Spaces,
79 StartOfTokenColumn, IndentedFromColumn, Newlines, "",
80 "", AlignedTo, InPPDirective && !Tok.IsFirst,
81 /*IsInsideToken=*/false));
82}
83
85 bool InPPDirective) {
86 if (Tok.Finalized || (Tok.MacroCtx && Tok.MacroCtx->Role == MR_ExpandedArg))
87 return;
88 Changes.push_back(Change(
89 Tok, /*CreateReplacement=*/false, Tok.WhitespaceRange, /*Spaces=*/0,
90 Tok.OriginalColumn, /*IndentedFromColumn=*/0, Tok.NewlinesBefore, "", "",
91 /*AlignedTo=*/nullptr, InPPDirective && !Tok.IsFirst,
92 /*IsInsideToken=*/false));
93}
94
95llvm::Error
97 return Replaces.add(Replacement);
98}
99
100bool WhitespaceManager::inputUsesCRLF(StringRef Text, bool DefaultToCRLF) {
101 size_t LF = Text.count('\n');
102 size_t CR = Text.count('\r') * 2;
103 return LF == CR ? DefaultToCRLF : CR > LF;
104}
105
107 const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
108 StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
109 unsigned Newlines, int Spaces) {
110 if (Tok.Finalized || (Tok.MacroCtx && Tok.MacroCtx->Role == MR_ExpandedArg))
111 return;
112 SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
113 Changes.push_back(
114 Change(Tok, /*CreateReplacement=*/true,
115 SourceRange(Start, Start.getLocWithOffset(ReplaceChars)), Spaces,
116 std::max(0, Spaces), /*IndentedFromColumn=*/0, Newlines,
117 PreviousPostfix, CurrentPrefix,
118 /*AlignedTo=*/&Tok, InPPDirective && !Tok.IsFirst,
119 /*IsInsideToken=*/true));
120}
121
123 if (Changes.empty())
124 return Replaces;
125
126 llvm::sort(Changes, Change::IsBeforeInFile(SourceMgr));
127 calculateLineBreakInformation();
128 alignConsecutiveMacros();
129 alignConsecutiveShortCaseStatements(/*IsExpr=*/true);
130 alignConsecutiveShortCaseStatements(/*IsExpr=*/false);
131 alignConsecutiveDeclarations();
132 alignConsecutiveBitFields();
133 alignConsecutiveAssignments();
134 if (Style.isTableGen()) {
135 alignConsecutiveTableGenBreakingDAGArgColons();
136 alignConsecutiveTableGenCondOperatorColons();
137 alignConsecutiveTableGenDefinitions();
138 }
139 alignChainedConditionals();
140 alignTrailingComments();
141 alignEscapedNewlines();
142 alignArrayInitializers();
143 generateChanges();
144
145 return Replaces;
146}
147
148void WhitespaceManager::calculateLineBreakInformation() {
149 Changes[0].PreviousEndOfTokenColumn = 0;
150 Change *LastOutsideTokenChange = &Changes[0];
151 for (unsigned I = 1, e = Changes.size(); I != e; ++I) {
152 auto &C = Changes[I];
153 auto &P = Changes[I - 1];
154 auto &PrevTokLength = P.TokenLength;
155 const auto *PP = I > 1 ? &Changes[I - 2] : nullptr;
156 SourceLocation OriginalWhitespaceStart =
157 C.OriginalWhitespaceRange.getBegin();
158 SourceLocation PreviousOriginalWhitespaceEnd =
159 P.OriginalWhitespaceRange.getEnd();
160 unsigned OriginalWhitespaceStartOffset =
161 SourceMgr.getFileOffset(OriginalWhitespaceStart);
162 unsigned PreviousOriginalWhitespaceEndOffset =
163 SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd);
164 assert(PreviousOriginalWhitespaceEndOffset <=
165 OriginalWhitespaceStartOffset);
166 const char *const PreviousOriginalWhitespaceEndData =
167 SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd);
168 StringRef Text(PreviousOriginalWhitespaceEndData,
169 SourceMgr.getCharacterData(OriginalWhitespaceStart) -
170 PreviousOriginalWhitespaceEndData);
171 // Usually consecutive changes would occur in consecutive tokens. This is
172 // not the case however when analyzing some preprocessor runs of the
173 // annotated lines. For example, in this code:
174 //
175 // #if A // line 1
176 // int i = 1;
177 // #else B // line 2
178 // int i = 2;
179 // #endif // line 3
180 //
181 // one of the runs will produce the sequence of lines marked with line 1, 2
182 // and 3. So the two consecutive whitespace changes just before '// line 2'
183 // and before '#endif // line 3' span multiple lines and tokens:
184 //
185 // #else B{change X}[// line 2
186 // int i = 2;
187 // ]{change Y}#endif // line 3
188 //
189 // For this reason, if the text between consecutive changes spans multiple
190 // newlines, the token length must be adjusted to the end of the original
191 // line of the token.
192 auto NewlinePos = Text.find_first_of('\n');
193 if (NewlinePos == StringRef::npos) {
194 PrevTokLength = OriginalWhitespaceStartOffset -
195 PreviousOriginalWhitespaceEndOffset +
196 C.PreviousLinePostfix.size() + P.CurrentLinePrefix.size();
197 if (!P.IsInsideToken)
198 PrevTokLength = std::min(PrevTokLength, P.Tok->ColumnWidth);
199 } else {
200 PrevTokLength = NewlinePos + P.CurrentLinePrefix.size();
201 }
202
203 // If there are multiple changes in this token, sum up all the changes until
204 // the end of the line.
205 if (P.IsInsideToken && P.NewlinesBefore == 0)
206 LastOutsideTokenChange->TokenLength += PrevTokLength + P.Spaces;
207 else
208 LastOutsideTokenChange = &P;
209
210 C.PreviousEndOfTokenColumn = P.StartOfTokenColumn + PrevTokLength;
211
212 P.IsTrailingComment =
213 (C.NewlinesBefore > 0 || C.Tok->is(tok::eof) ||
214 (C.IsInsideToken && C.Tok->is(tok::comment))) &&
215 P.Tok->is(tok::comment) &&
216 (P.NewlinesBefore == 0 || !PP || PP->IsTrailingComment) &&
217 // FIXME: This is a dirty hack. The problem is that
218 // BreakableLineCommentSection does comment reflow changes and here is
219 // the aligning of trailing comments. Consider the case where we reflow
220 // the second line up in this example:
221 //
222 // // line 1
223 // // line 2
224 //
225 // That amounts to 2 changes by BreakableLineCommentSection:
226 // - the first, delimited by (), for the whitespace between the tokens,
227 // - and second, delimited by [], for the whitespace at the beginning
228 // of the second token:
229 //
230 // // line 1(
231 // )[// ]line 2
232 //
233 // So in the end we have two changes like this:
234 //
235 // // line1()[ ]line 2
236 //
237 // Note that the OriginalWhitespaceStart of the second change is the
238 // same as the PreviousOriginalWhitespaceEnd of the first change.
239 // In this case, the below check ensures that the second change doesn't
240 // get treated as a trailing comment change here, since this might
241 // trigger additional whitespace to be wrongly inserted before "line 2"
242 // by the comment aligner here.
243 //
244 // For a proper solution we need a mechanism to say to WhitespaceManager
245 // that a particular change breaks the current sequence of trailing
246 // comments.
247 OriginalWhitespaceStart != PreviousOriginalWhitespaceEnd;
248 }
249 // FIXME: The last token is currently not always an eof token; in those
250 // cases, setting TokenLength of the last token to 0 is wrong.
251 Changes.back().TokenLength = 0;
252 Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment);
253
254 const WhitespaceManager::Change *LastBlockComment = nullptr;
255 for (auto &Change : Changes) {
256 // Reset the IsTrailingComment flag for changes inside of trailing comments
257 // so they don't get realigned later. Comment line breaks however still need
258 // to be aligned.
261 Change.StartOfBlockComment = nullptr;
263 if (Change.Tok->is(tok::comment)) {
264 if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) {
265 LastBlockComment = &Change;
266 } else if ((Change.StartOfBlockComment = LastBlockComment)) {
270 }
271 } else {
272 LastBlockComment = nullptr;
273 }
274 }
275
276 // Compute conditional nesting level
277 // Level is increased for each conditional, unless this conditional continues
278 // a chain of conditional, i.e. starts immediately after the colon of another
279 // conditional.
280 SmallVector<bool, 16> ScopeStack;
281 int ConditionalsLevel = 0;
282 for (auto &Change : Changes) {
283 for (unsigned i = 0, e = Change.Tok->FakeLParens.size(); i != e; ++i) {
284 bool isNestedConditional =
285 Change.Tok->FakeLParens[e - 1 - i] == prec::Conditional &&
286 !(i == 0 && Change.Tok->Previous &&
287 Change.Tok->Previous->is(TT_ConditionalExpr) &&
288 Change.Tok->Previous->is(tok::colon));
289 if (isNestedConditional)
290 ++ConditionalsLevel;
291 ScopeStack.push_back(isNestedConditional);
292 }
293
294 Change.ConditionalsLevel = ConditionalsLevel;
295
296 for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size(); --i)
297 if (ScopeStack.pop_back_val())
298 --ConditionalsLevel;
299 }
300}
301
302// Sets the spaces in front of a Change, and updates the start/end columns of
303// subsequent tokens so that trailing comments and escaped newlines can be
304// aligned properly.
305static void
306SetChangeSpaces(unsigned Start, unsigned Spaces,
308 auto &FirstChange = Changes[Start];
309 const int ColumnChange = Spaces - FirstChange.Spaces;
310
311 if (ColumnChange == 0)
312 return;
313
314 FirstChange.Spaces += ColumnChange;
315 FirstChange.StartOfTokenColumn += ColumnChange;
316
317 for (auto I = Start + 1; I < Changes.size(); I++) {
318 auto &Change = Changes[I];
319
320 Change.PreviousEndOfTokenColumn += ColumnChange;
321
322 if (Change.NewlinesBefore > 0)
323 break;
324
325 Change.StartOfTokenColumn += ColumnChange;
326 }
327}
328
329// Changes the spaces in front of a change by Delta, and updates the start/end
330// columns of subsequent tokens so that trailing comments and escaped newlines
331// can be aligned properly.
332static void
333IncrementChangeSpaces(unsigned Start, int Delta,
335 assert(Delta > 0 || (abs(Delta) <= Changes[Start].Spaces));
336 SetChangeSpaces(Start, Changes[Start].Spaces + Delta, Changes);
337}
338
339// Align a single sequence of tokens, see AlignTokens below.
340// Column - The tokens indexed in Matches are moved to this column.
341// RightJustify - Whether it is the token's right end or left end that gets
342// moved to that column.
343static void
344AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
345 unsigned Column, bool RightJustify,
346 ArrayRef<unsigned> Matches,
348 unsigned OriginalMatchColumn = 0;
349 int Shift = 0;
350
351 // ScopeStack keeps track of the current scope depth. It contains the levels
352 // of at most 2 scopes. The first one is the one that the matched token is
353 // in. The second one is the one that should not be moved by this procedure.
354 // The "Matches" indices should only have tokens from the outer-most scope.
355 // However, we do need to pay special attention to one class of tokens
356 // that are not in the outer-most scope, and that is the continuations of an
357 // unwrapped line whose positions are derived from a token to the right of the
358 // aligned token, as illustrated by this example:
359 // double a(int x);
360 // int b(int y,
361 // double z);
362 // In the above example, we need to take special care to ensure that
363 // 'double z' is indented along with its owning function 'b', because its
364 // position is derived from the '(' token to the right of the 'b' token.
365 // The same holds for calling a function:
366 // double a = foo(x);
367 // int b = bar(foo(y),
368 // foor(z));
369 // Similar for broken string literals:
370 // double x = 3.14;
371 // auto s = "Hello"
372 // "World";
373 // Special handling is required for 'nested' ternary operators.
375
376 for (unsigned i = Start; i != End; ++i) {
377 auto &CurrentChange = Changes[i];
378 if (!Matches.empty() && Matches[0] < i)
379 Matches.consume_front();
380 assert(Matches.empty() || Matches[0] >= i);
381 while (!ScopeStack.empty() &&
382 CurrentChange.indentAndNestingLevel() < ScopeStack.back()) {
383 ScopeStack.pop_back();
384 }
385
386 // Keep track of the level that should not move with the aligned token.
387 if (ScopeStack.size() == 1u && CurrentChange.NewlinesBefore != 0u &&
388 CurrentChange.indentAndNestingLevel() > ScopeStack[0] &&
389 CurrentChange.IndentedFromColumn < OriginalMatchColumn) {
390 ScopeStack.push_back(CurrentChange.indentAndNestingLevel());
391 }
392
393 bool InsideNestedScope =
394 !ScopeStack.empty() &&
395 (CurrentChange.indentAndNestingLevel() > ScopeStack[0] ||
396 (CurrentChange.indentAndNestingLevel() == ScopeStack[0] &&
397 CurrentChange.IndentedFromColumn >= OriginalMatchColumn));
398
399 if (CurrentChange.NewlinesBefore > 0 && !InsideNestedScope)
400 Shift = 0;
401
402 // If this is the first matching token to be aligned, remember by how many
403 // spaces it has to be shifted, so the rest of the changes on the line are
404 // shifted by the same amount
405 if (!Matches.empty() && Matches[0] == i) {
406 OriginalMatchColumn = CurrentChange.StartOfTokenColumn;
407 Shift = Column - (RightJustify ? CurrentChange.TokenLength : 0) -
408 CurrentChange.StartOfTokenColumn;
409 ScopeStack = {CurrentChange.indentAndNestingLevel()};
410 }
411
412 if (Shift == 0)
413 continue;
414
415 // This is for lines that are split across multiple lines, as mentioned in
416 // the ScopeStack comment. The stack size being 1 means that the token is
417 // not in a scope that should not move.
418 if ((!Matches.empty() && Matches[0] == i) ||
419 (ScopeStack.size() == 1u && CurrentChange.NewlinesBefore > 0 &&
420 InsideNestedScope)) {
421 CurrentChange.IndentedFromColumn += Shift;
422 IncrementChangeSpaces(i, Shift, Changes);
423 }
424
425 // We should not remove required spaces unless we break the line before.
426 assert(Shift > 0 || Changes[i].NewlinesBefore > 0 ||
427 CurrentChange.Spaces >=
428 static_cast<int>(Changes[i].Tok->SpacesRequiredBefore) ||
429 CurrentChange.Tok->is(tok::eof));
430
431 // If PointerAlignment is PAS_Right, keep *s or &s next to the token,
432 // except if the token is equal, then a space is needed.
433 if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
434 Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
435 CurrentChange.Spaces != 0 &&
436 CurrentChange.Tok->isNoneOf(tok::equal, tok::r_paren,
437 TT_TemplateCloser)) {
438 const bool ReferenceNotRightAligned =
439 Style.ReferenceAlignment != FormatStyle::RAS_Right &&
440 Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
441 for (int Previous = i - 1;
442 Previous >= 0 && Changes[Previous].Tok->is(TT_PointerOrReference);
443 --Previous) {
444 assert(Changes[Previous].Tok->isPointerOrReference());
445 if (Changes[Previous].Tok->isNot(tok::star)) {
446 if (ReferenceNotRightAligned)
447 continue;
448 } else if (Style.PointerAlignment != FormatStyle::PAS_Right) {
449 continue;
450 }
451
452 IncrementChangeSpaces(Previous + 1, -Shift, Changes);
453 IncrementChangeSpaces(Previous, Shift, Changes);
454 }
455 }
456 }
457}
458
459namespace {
460enum class AlignStrategy { Normal, Macro, CaseBody, CaseColon };
461} // namespace
462
463// Walk through a subset of the changes, starting at StartAt, and find
464// sequences of matching tokens to align. To do so, keep track of the lines and
465// whether or not a matching token was found on a line. If a matching token is
466// found, extend the current sequence. If the current line cannot be part of a
467// sequence, e.g. because there is an empty line before it or it contains only
468// non-matching tokens, finalize the previous sequence.
469// The value returned is the token on which we stopped, either because we
470// exhausted all items inside Changes, or because we hit a scope level higher
471// than our initial scope.
472// This function is recursive. Each invocation processes only the scope level
473// equal to the initial level, which is the level of Changes[StartAt].
474// If we encounter a scope level greater than the initial level, then we call
475// ourselves recursively, thereby avoiding the pollution of the current state
476// with the alignment requirements of the nested sub-level. This recursive
477// behavior is necessary for aligning function prototypes that have one or more
478// arguments.
479// If this function encounters a scope level less than the initial level,
480// it returns the current position.
481// There is a non-obvious subtlety in the recursive behavior: Even though we
482// defer processing of nested levels to recursive invocations of this
483// function, when it comes time to align a sequence of tokens, we run the
484// alignment on the entire sequence, including the nested levels.
485// When doing so, most of the nested tokens are skipped, because their
486// alignment was already handled by the recursive invocations of this function.
487// However, the special exception is that we do NOT skip function parameters
488// that are split across multiple lines. See the test case in FormatTest.cpp
489// that mentions "split function parameter alignment" for an example of this.
490// When the parameter RightJustify is true, the operator will be
491// right-justified. It is used to align compound assignments like `+=` and `=`.
492// When RightJustify and ACS.PadOperators are true, operators in each block to
493// be aligned will be padded on the left to the same length before aligning.
494//
495// For the Macro, CaseBody, or CaseColon strategies we will not look at the
496// indentaion and nesting level to recurse into the line for alignment. We will
497// also not count the commas.
498//
499// The CaseBody and CaseColon strategies also have some special handling,
500// because we need to be able align empty cases (rsp. use the position to push
501// out other case bodies), but stop on non short cases, which needs a bit of
502// lookahead.
503template <typename F, AlignStrategy Strategy = AlignStrategy::Normal>
504static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
506 unsigned StartAt,
508 bool RightJustify = false) {
509 // We arrange each line in 3 parts. The operator to be aligned (the anchor),
510 // and text to its left and right. In the aligned text the width of each part
511 // will be the maximum of that over the block that has been aligned.
512
513 // Maximum widths of each part so far.
514 // When RightJustify is true and ACS.PadOperators is false, the part from
515 // start of line to the right end of the anchor. Otherwise, only the part to
516 // the left of the anchor. Including the space that exists on its left from
517 // the start. Not including the padding added on the left to right-justify the
518 // anchor.
519 unsigned WidthLeft = 0;
520 // The operator to be aligned when RightJustify is true and ACS.PadOperators
521 // is false. 0 otherwise.
522 unsigned WidthAnchor = 0;
523 // Width to the right of the anchor. Plus width of the anchor when
524 // RightJustify is false.
525 unsigned WidthRight = 0;
526
527 // Number of the start and the end of the current token sequence.
528 unsigned StartOfSequence = 0;
529 unsigned EndOfSequence = 0;
530
531 // The positions of the tokens to be aligned.
532 SmallVector<unsigned> MatchedIndices;
533
534 // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
535 // abort when we hit any token in a higher scope than the starting one.
536 const auto IndentAndNestingLevel =
537 StartAt < Changes.size() ? Changes[StartAt].indentAndNestingLevel()
538 : std::tuple<unsigned, unsigned, unsigned>();
539
540 // Keep track of the number of commas before the matching tokens, we will only
541 // align a sequence of matching tokens if they are preceded by the same number
542 // of commas.
543 unsigned CommasBeforeLastMatch = 0;
544 unsigned CommasBeforeMatch = 0;
545
546 // The column number of the matching token on the current line.
547 std::optional<unsigned> MatchingColumn;
548
549 // Whether the current line consists purely of comments.
550 bool LineIsComment = true;
551
552 // Aligns a sequence of matching tokens, on the MinColumn column.
553 //
554 // Sequences start from the first matching token to align, and end at the
555 // first token of the first line that doesn't need to be aligned.
556 //
557 // We need to adjust the StartOfTokenColumn of each Change that is on a line
558 // containing any matching token to be aligned and located after such token.
559 auto AlignCurrentSequence = [&] {
560 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
561 AlignTokenSequence(Style, StartOfSequence, EndOfSequence,
562 WidthLeft + WidthAnchor, RightJustify, MatchedIndices,
563 Changes);
564 }
565 WidthLeft = 0;
566 WidthAnchor = 0;
567 WidthRight = 0;
568 StartOfSequence = 0;
569 EndOfSequence = 0;
570 MatchedIndices.clear();
571 };
572
573 unsigned I = StartAt;
574 const auto E = Changes.size();
575 for (const auto LoopEnd = Strategy == AlignStrategy::CaseBody ? E - 1 : E;
576 I != LoopEnd; ++I) {
577 auto &CurrentChange = Changes[I];
578 if (CurrentChange.indentAndNestingLevel() < IndentAndNestingLevel)
579 break;
580
581 if (CurrentChange.NewlinesBefore != 0) {
582 CommasBeforeMatch = 0;
583 EndOfSequence = I;
584
585 // Whether to break the alignment sequence because of an empty line.
586 bool EmptyLineBreak =
587 (CurrentChange.NewlinesBefore > 1) && !ACS.AcrossEmptyLines;
588
589 // Whether to break the alignment sequence because of a line without a
590 // match.
591 bool NoMatchBreak =
592 !MatchingColumn && !(LineIsComment && ACS.AcrossComments);
593
594 if (EmptyLineBreak || NoMatchBreak)
595 AlignCurrentSequence();
596
597 // A new line starts, re-initialize line status tracking bools.
598 // Keep the match state if a string literal is continued on this line.
599 if (MatchingColumn && CurrentChange.IndentedFromColumn < *MatchingColumn)
600 MatchingColumn.reset();
601 LineIsComment = true;
602 }
603
604 if (CurrentChange.Tok->isNot(tok::comment))
605 LineIsComment = false;
606
607 if constexpr (Strategy == AlignStrategy::Normal) {
608 if (CurrentChange.Tok->is(tok::comma)) {
609 ++CommasBeforeMatch;
610 } else if (CurrentChange.indentAndNestingLevel() >
611 IndentAndNestingLevel) {
612 // Call AlignTokens recursively, skipping over this scope block.
613 const auto StoppedAt = AlignTokens<F &, Strategy>(
614 Style, Matches, Changes, I, ACS, RightJustify);
615 I = StoppedAt - 1;
616 continue;
617 }
618 }
619
620 if (!Matches(CurrentChange))
621 continue;
622
623 const auto IndexToAlign = Strategy == AlignStrategy::CaseBody ? I + 1 : I;
624 const auto &ChangeToAlign = Changes[IndexToAlign];
625 const auto [AlignTheToken,
626 ShiftAlignment] = [&]() -> std::pair<bool, bool> {
627 switch (Strategy) {
628 case AlignStrategy::CaseBody: {
629 if (ChangeToAlign.NewlinesBefore == 0)
630 return {true, false};
631 const auto *Tok = ChangeToAlign.Tok;
632 if (Tok->is(tok::comment) && ACS.AcrossComments)
633 Tok = Tok->getNextNonComment();
634 return {false, Tok && Tok->isOneOf(tok::kw_case, tok::kw_default)};
635 }
636 case AlignStrategy::CaseColon: {
637 if (I + 1 == LoopEnd)
638 return {true, false};
639 const auto &NextChange = Changes[I + 1];
640 if (NextChange.NewlinesBefore == 0 ||
641 (CurrentChange.Tok->Next &&
642 CurrentChange.Tok->Next->isTrailingComment())) {
643 return {true, false};
644 }
645 const auto *Tok = NextChange.Tok;
646 if (Tok->is(tok::comment) && ACS.AcrossComments)
647 Tok = Tok->getNextNonComment();
648 return {Tok && Tok->isOneOf(tok::kw_case, tok::kw_default), false};
649 }
650 default: // AlignStrategy::Macro and AlignStrategy::Normal:
651 return {true, false};
652 }
653 }();
654
655 if (!AlignTheToken && !ShiftAlignment)
656 continue;
657
658 // If there is more than one matching token per line, or if the number of
659 // preceding commas, do not match anymore, end the sequence.
660 if ((ChangeToAlign.NewlinesBefore == 0U && MatchingColumn) ||
661 CommasBeforeMatch != CommasBeforeLastMatch) {
662 MatchedIndices.push_back(IndexToAlign);
663 AlignCurrentSequence();
664 }
665
666 CommasBeforeLastMatch = CommasBeforeMatch;
667 MatchingColumn = AlignTheToken ? ChangeToAlign.StartOfTokenColumn
668 : std::numeric_limits<unsigned>::max();
669
670 if (StartOfSequence == 0 && AlignTheToken)
671 StartOfSequence = IndexToAlign;
672
673 unsigned ChangeWidthLeft = ChangeToAlign.StartOfTokenColumn;
674 unsigned ChangeWidthAnchor = 0;
675 unsigned ChangeWidthRight = 0;
676 unsigned CurrentChangeWidthRight = 0;
677 if (!AlignTheToken) {
678 // When not aligning the token, we align case bodies, and the case is
679 // empty, thus we only adapt the position and have nothing to be aligned.
680 // This is needed, because an empty body may push out the alignment.
681 ChangeWidthLeft = CurrentChange.StartOfTokenColumn +
682 CurrentChange.TokenLength +
683 /*Space after the colon/arrow=*/1;
684 } else {
685 if (RightJustify)
686 if (ACS.PadOperators)
687 ChangeWidthAnchor = ChangeToAlign.TokenLength;
688 else
689 ChangeWidthLeft += ChangeToAlign.TokenLength;
690 else
691 CurrentChangeWidthRight = ChangeToAlign.TokenLength;
692 const FormatToken *MatchingParenToEncounter = nullptr;
693 for (unsigned J = IndexToAlign + 1;
694 J != E && (Changes[J].NewlinesBefore == 0 ||
695 MatchingParenToEncounter || Changes[J].AlignedTo);
696 ++J) {
697 const auto &Change = Changes[J];
698 const auto *Tok = Change.Tok;
699
700 if (Tok->MatchingParen) {
701 if (Tok->isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
702 TT_TemplateOpener) &&
703 !MatchingParenToEncounter) {
704 // If the next token is on the next line, we probably don't need to
705 // check the following lengths, because it most likely isn't aligned
706 // with the rest.
707 if (J + 1 != E && Changes[J + 1].NewlinesBefore == 0)
708 MatchingParenToEncounter = Tok->MatchingParen;
709 } else if (MatchingParenToEncounter == Tok->MatchingParen) {
710 MatchingParenToEncounter = nullptr;
711 }
712 }
713
714 if (Change.NewlinesBefore != 0) {
715 ChangeWidthRight =
716 std::max(ChangeWidthRight, CurrentChangeWidthRight);
717 const auto ChangeWidthStart = ChangeWidthLeft + ChangeWidthAnchor;
718 // If the position of the current token is columnwise before the begin
719 // of the alignment, we drop out here, because the next line does not
720 // have to be moved with the previous one(s) for the alignment. E.g.:
721 // int i1 = 1; | <- ColumnLimit | int i1 = 1;
722 // int j = 0; | Without the break -> | int j = 0;
723 // int k = bar( | We still want to align the = | int k = bar(
724 // argument1, | here, even if we can't move | argument1,
725 // argument2); | the following lines. | argument2);
726 if (Change.IndentedFromColumn < ChangeWidthStart)
727 break;
728 CurrentChangeWidthRight = Change.Spaces - ChangeWidthStart;
729 } else {
730 CurrentChangeWidthRight += Change.Spaces;
731 }
732
733 // Changes are generally 1:1 with the tokens, but a change could also be
734 // inside of a token, in which case it's counted more than once: once
735 // for the whitespace surrounding the token (!IsInsideToken) and once
736 // for each whitespace change within it (IsInsideToken). Therefore,
737 // changes inside of a token should only count the space.
739 CurrentChangeWidthRight += Change.TokenLength;
740 }
741
742 ChangeWidthRight = std::max(ChangeWidthRight, CurrentChangeWidthRight);
743 }
744
745 // If we are restricted by the maximum column width, end the sequence.
746 unsigned NewLeft = std::max(ChangeWidthLeft, WidthLeft);
747 unsigned NewAnchor = std::max(ChangeWidthAnchor, WidthAnchor);
748 unsigned NewRight = std::max(ChangeWidthRight, WidthRight);
749 // `ColumnLimit == 0` means there is no column limit.
750 if (Style.ColumnLimit != 0 &&
751 Style.ColumnLimit < NewLeft + NewAnchor + NewRight) {
752 AlignCurrentSequence();
753 StartOfSequence = AlignTheToken ? IndexToAlign : 0;
754 WidthLeft = ChangeWidthLeft;
755 WidthAnchor = ChangeWidthAnchor;
756 WidthRight = ChangeWidthRight;
757 } else {
758 WidthLeft = NewLeft;
759 WidthAnchor = NewAnchor;
760 WidthRight = NewRight;
761 }
762 if (AlignTheToken)
763 MatchedIndices.push_back(IndexToAlign);
764 }
765
766 // Pass entire lines to the function so that it can update the state of all
767 // tokens that move.
768 for (EndOfSequence = I;
769 EndOfSequence < E && Changes[EndOfSequence].NewlinesBefore == 0;
770 ++EndOfSequence) {
771 }
772 AlignCurrentSequence();
773 // The return value should still be where the level ends. The rest of the line
774 // may contain stuff to be aligned within an outer level.
775 return I;
776}
777
778void WhitespaceManager::alignConsecutiveMacros() {
779 if (!Style.AlignConsecutiveMacros.Enabled)
780 return;
781
782 auto AlignMacrosMatches = [](const Change &C) {
783 const FormatToken *Current = C.Tok;
784 assert(Current);
785
786 if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
787 return false;
788
789 Current = Current->Previous;
790
791 // If token is a ")", skip over the parameter list, to the
792 // token that precedes the "("
793 if (Current->is(tok::r_paren)) {
794 const auto *MatchingParen = Current->MatchingParen;
795 // For a macro function, 0 spaces are required between the
796 // identifier and the lparen that opens the parameter list.
797 if (!MatchingParen || MatchingParen->SpacesRequiredBefore > 0 ||
798 !MatchingParen->Previous) {
799 return false;
800 }
801 Current = MatchingParen->Previous;
802 } else if (Current->Next->SpacesRequiredBefore != 1) {
803 // For a simple macro, 1 space is required between the
804 // identifier and the first token of the defined value.
805 return false;
806 }
807
808 return Current->endsSequence(tok::identifier, tok::pp_define);
809 };
810
812 Style, AlignMacrosMatches, Changes, 0, Style.AlignConsecutiveMacros);
813}
814
815void WhitespaceManager::alignConsecutiveAssignments() {
816 if (!Style.AlignConsecutiveAssignments.Enabled &&
817 !Style.AlignConsecutiveAssignments.EnumAssignments) {
818 return;
819 }
820
822 Style,
823 [&](const Change &C) {
824 // Do not align on equal signs that are first on a line.
825 if (C.NewlinesBefore > 0)
826 return false;
827
828 // Do not align on equal signs that are last on a line.
829 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
830 return false;
831
832 // Align enum '=' when EnumAssignments is enabled.
833 if (Style.AlignConsecutiveAssignments.EnumAssignments &&
834 C.Tok->is(TT_EnumEqual)) {
835 return true;
836 }
837
838 if (!Style.AlignConsecutiveAssignments.Enabled)
839 return false;
840
841 // Do not align operator= overloads.
842 FormatToken *Previous = C.Tok->getPreviousNonComment();
843 if (Previous && Previous->is(tok::kw_operator))
844 return false;
845
846 return Style.AlignConsecutiveAssignments.AlignCompound
847 ? C.Tok->getPrecedence() == prec::Assignment
848 : (C.Tok->is(tok::equal) ||
849 // In Verilog the '<=' is not a compound assignment, thus
850 // it is aligned even when the AlignCompound option is not
851 // set.
852 (Style.isVerilog() && C.Tok->is(tok::lessequal) &&
853 C.Tok->getPrecedence() == prec::Assignment));
854 },
855 Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments,
856 /*RightJustify=*/true);
857}
858
859void WhitespaceManager::alignConsecutiveBitFields() {
860 alignConsecutiveColons(Style.AlignConsecutiveBitFields, TT_BitFieldColon);
861}
862
863void WhitespaceManager::alignConsecutiveColons(
864 const FormatStyle::AlignConsecutiveStyle &AlignStyle, TokenType Type) {
865 if (!AlignStyle.Enabled)
866 return;
867
869 Style,
870 [&](Change const &C) {
871 // Do not align on ':' that is first on a line.
872 if (C.NewlinesBefore > 0)
873 return false;
874
875 // Do not align on ':' that is last on a line.
876 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
877 return false;
878
879 return C.Tok->is(Type);
880 },
881 Changes, /*StartAt=*/0, AlignStyle);
882}
883
884void WhitespaceManager::alignConsecutiveShortCaseStatements(bool IsExpr) {
885 if (!Style.AlignConsecutiveShortCaseStatements.Enabled ||
886 !(IsExpr ? Style.AllowShortCaseExpressionOnASingleLine
887 : Style.AllowShortCaseLabelsOnASingleLine)) {
888 return;
889 }
890
891 const auto Type = IsExpr ? TT_CaseLabelArrow : TT_CaseLabelColon;
892 const auto &Option = Style.AlignConsecutiveShortCaseStatements;
893 const bool AlignArrowOrColon =
894 IsExpr ? Option.AlignCaseArrows : Option.AlignCaseColons;
895
896 FormatStyle::AlignConsecutiveStyle AlignStyle{};
897 AlignStyle.AcrossComments = Option.AcrossComments;
898 AlignStyle.AcrossEmptyLines = Option.AcrossEmptyLines;
899
900 auto Matches = [Type](const Change &C) { return C.Tok->is(Type); };
901 if (AlignArrowOrColon) {
903 Style, Matches, Changes, /*StartAt=*/0, AlignStyle);
904 } else {
906 Style, Matches, Changes, /*StartAt=*/0, AlignStyle);
907 }
908}
909
910void WhitespaceManager::alignConsecutiveTableGenBreakingDAGArgColons() {
911 alignConsecutiveColons(Style.AlignConsecutiveTableGenBreakingDAGArgColons,
912 TT_TableGenDAGArgListColonToAlign);
913}
914
915void WhitespaceManager::alignConsecutiveTableGenCondOperatorColons() {
916 alignConsecutiveColons(Style.AlignConsecutiveTableGenCondOperatorColons,
917 TT_TableGenCondOperatorColon);
918}
919
920void WhitespaceManager::alignConsecutiveTableGenDefinitions() {
921 alignConsecutiveColons(Style.AlignConsecutiveTableGenDefinitionColons,
922 TT_InheritanceColon);
923}
924
925void WhitespaceManager::alignConsecutiveDeclarations() {
926 if (!Style.AlignConsecutiveDeclarations.Enabled)
927 return;
928
930 Style,
931 [&](Change const &C) {
932 if (C.Tok->is(TT_FunctionTypeLParen))
933 return Style.AlignConsecutiveDeclarations.AlignFunctionPointers;
934 if (C.Tok->is(TT_FunctionDeclarationName))
935 return Style.AlignConsecutiveDeclarations.AlignFunctionDeclarations;
936 if (C.Tok->isNot(TT_StartOfName))
937 return false;
938 if (C.Tok->Previous &&
939 C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
940 return false;
941 // Check if there is a subsequent name that starts the same declaration.
942 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
943 if (Next->is(tok::comment))
944 continue;
945 if (Next->is(TT_PointerOrReference))
946 return false;
947 if (!Next->Tok.getIdentifierInfo())
948 break;
949 if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
950 tok::kw_operator)) {
951 return false;
952 }
953 }
954 return true;
955 },
956 Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
957}
958
959void WhitespaceManager::alignChainedConditionals() {
960 if (Style.BreakBeforeTernaryOperators) {
962 Style,
963 [](Change const &C) {
964 // Align question operators and last colon
965 return C.Tok->is(TT_ConditionalExpr) &&
966 ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
967 (C.Tok->is(tok::colon) && C.Tok->Next &&
968 (C.Tok->Next->FakeLParens.empty() ||
969 C.Tok->Next->FakeLParens.back() != prec::Conditional)));
970 },
971 Changes, /*StartAt=*/0);
972 } else {
973 static auto AlignWrappedOperand = [](Change const &C) {
974 FormatToken *Previous = C.Tok->getPreviousNonComment();
975 return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
976 (Previous->is(tok::colon) &&
977 (C.Tok->FakeLParens.empty() ||
978 C.Tok->FakeLParens.back() != prec::Conditional));
979 };
980 // Ensure we keep alignment of wrapped operands with non-wrapped operands
981 // Since we actually align the operators, the wrapped operands need the
982 // extra offset to be properly aligned.
983 for (Change &C : Changes)
984 if (AlignWrappedOperand(C))
985 C.StartOfTokenColumn -= 2;
987 Style,
988 [this](Change const &C) {
989 // Align question operators if next operand is not wrapped, as
990 // well as wrapped operands after question operator or last
991 // colon in conditional sequence
992 return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
993 &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
994 !(&C + 1)->IsTrailingComment) ||
995 AlignWrappedOperand(C);
996 },
997 Changes, /*StartAt=*/0);
998 }
999}
1000
1001void WhitespaceManager::alignTrailingComments() {
1002 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
1003 return;
1004
1005 const int Size = Changes.size();
1006 if (Size == 0)
1007 return;
1008
1009 int MinColumn = 0;
1010 int StartOfSequence = 0;
1011 bool BreakBeforeNext = false;
1012 bool IsInPP = Changes.front().Tok->Tok.is(tok::hash);
1013 int NewLineThreshold = 1;
1014 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
1015 NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
1016
1017 for (int I = 0, MaxColumn = INT_MAX, Newlines = 0; I < Size; ++I) {
1018 auto &C = Changes[I];
1019 if (C.StartOfBlockComment)
1020 continue;
1021 if (C.NewlinesBefore != 0) {
1022 Newlines += C.NewlinesBefore;
1023 const bool WasInPP = std::exchange(
1024 IsInPP, C.Tok->Tok.is(tok::hash) || (IsInPP && C.IsTrailingComment) ||
1025 C.ContinuesPPDirective);
1026 if (IsInPP != WasInPP && !Style.AlignTrailingComments.AlignPPAndNotPP) {
1027 alignTrailingComments(StartOfSequence, I, MinColumn);
1028 MinColumn = 0;
1029 MaxColumn = INT_MAX;
1030 StartOfSequence = I;
1031 Newlines = 0;
1032 }
1033 }
1034 if (NewLineThreshold > 1 && C.Tok->is(BK_Block)) {
1035 alignTrailingComments(StartOfSequence, I, MinColumn);
1036 MinColumn = 0;
1037 MaxColumn = INT_MAX;
1038 StartOfSequence = I + 1;
1039 Newlines = 0;
1040 continue;
1041 }
1042 if (!C.IsTrailingComment)
1043 continue;
1044
1045 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1046 const int OriginalSpaces =
1047 C.OriginalWhitespaceRange.getEnd().getRawEncoding() -
1048 C.OriginalWhitespaceRange.getBegin().getRawEncoding() -
1049 C.Tok->LastNewlineOffset;
1050 assert(OriginalSpaces >= 0);
1051 const auto RestoredLineLength =
1052 C.StartOfTokenColumn + C.TokenLength + OriginalSpaces;
1053 // If leaving comments makes the line exceed the column limit, give up to
1054 // leave the comments.
1055 if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit > 0)
1056 break;
1057
1058 int Spaces =
1059 C.NewlinesBefore > 0 ? C.Tok->OriginalColumn : OriginalSpaces;
1060 setChangeSpaces(I, Spaces);
1061 continue;
1062 }
1063
1064 const int ChangeMinColumn = C.StartOfTokenColumn;
1065 int ChangeMaxColumn;
1066
1067 // If we don't create a replacement for this change, we have to consider
1068 // it to be immovable.
1069 if (!C.CreateReplacement)
1070 ChangeMaxColumn = ChangeMinColumn;
1071 else if (Style.ColumnLimit == 0)
1072 ChangeMaxColumn = INT_MAX;
1073 else if (Style.ColumnLimit >= C.TokenLength)
1074 ChangeMaxColumn = Style.ColumnLimit - C.TokenLength;
1075 else
1076 ChangeMaxColumn = ChangeMinColumn;
1077
1078 if (I + 1 < Size && Changes[I + 1].ContinuesPPDirective &&
1079 ChangeMaxColumn >= 2) {
1080 ChangeMaxColumn -= 2;
1081 }
1082
1083 bool WasAlignedWithStartOfNextLine = false;
1084 if (C.NewlinesBefore >= 1) { // A comment on its own line.
1085 const auto CommentColumn =
1086 SourceMgr.getSpellingColumnNumber(C.OriginalWhitespaceRange.getEnd());
1087 for (int J = I + 1; J < Size; ++J) {
1088 if (Changes[J].Tok->is(tok::comment))
1089 continue;
1090
1091 if (!C.AlignedTo)
1092 C.AlignedTo = C.Tok->getPrevious(tok::comment);
1093 const auto NextColumn = SourceMgr.getSpellingColumnNumber(
1094 Changes[J].OriginalWhitespaceRange.getEnd());
1095 // The start of the next token was previously aligned with the
1096 // start of this comment.
1097 WasAlignedWithStartOfNextLine =
1098 CommentColumn == NextColumn ||
1099 CommentColumn == NextColumn + Style.IndentWidth;
1100 break;
1101 }
1102 }
1103
1104 // We don't want to align comments which end a scope, which are here
1105 // identified by most closing braces.
1106 auto DontAlignThisComment = [](const auto *Tok) {
1107 if (Tok->is(tok::semi)) {
1108 Tok = Tok->getPreviousNonComment();
1109 if (!Tok)
1110 return false;
1111 }
1112 if (Tok->is(tok::r_paren)) {
1113 // Back up past the parentheses and a `TT_DoWhile` that may precede.
1114 Tok = Tok->MatchingParen;
1115 if (!Tok)
1116 return false;
1117 Tok = Tok->getPreviousNonComment();
1118 if (!Tok)
1119 return false;
1120 if (Tok->is(TT_DoWhile)) {
1121 const auto *Prev = Tok->getPreviousNonComment();
1122 if (!Prev) {
1123 // A do-while-loop without braces.
1124 return true;
1125 }
1126 Tok = Prev;
1127 }
1128 }
1129
1130 if (Tok->isNot(tok::r_brace))
1131 return false;
1132
1133 while (Tok->Previous && Tok->Previous->is(tok::r_brace))
1134 Tok = Tok->Previous;
1135 return Tok->NewlinesBefore > 0;
1136 };
1137
1138 if (I > 0 && C.NewlinesBefore == 0 &&
1139 DontAlignThisComment(Changes[I - 1].Tok)) {
1140 alignTrailingComments(StartOfSequence, I, MinColumn);
1141 // Reset to initial values, but skip this change for the next alignment
1142 // pass.
1143 MinColumn = 0;
1144 MaxColumn = INT_MAX;
1145 StartOfSequence = I + 1;
1146 } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
1147 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1148 // Break the comment sequence if the previous line did not end
1149 // in a trailing comment.
1150 (C.NewlinesBefore == 1 && I > 0 &&
1151 !Changes[I - 1].IsTrailingComment) ||
1152 WasAlignedWithStartOfNextLine) {
1153 alignTrailingComments(StartOfSequence, I, MinColumn);
1154 MinColumn = ChangeMinColumn;
1155 MaxColumn = ChangeMaxColumn;
1156 StartOfSequence = I;
1157 } else {
1158 MinColumn = std::max(MinColumn, ChangeMinColumn);
1159 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1160 }
1161 BreakBeforeNext = (I == 0) || (C.NewlinesBefore > 1) ||
1162 // Never start a sequence with a comment at the beginning
1163 // of the line.
1164 (C.NewlinesBefore == 1 && StartOfSequence == I);
1165 Newlines = 0;
1166 }
1167 alignTrailingComments(StartOfSequence, Size, MinColumn);
1168}
1169
1170void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
1171 unsigned Column) {
1172 for (unsigned i = Start; i != End; ++i) {
1173 int Shift = 0;
1174 if (Changes[i].IsTrailingComment)
1175 Shift = Column - Changes[i].StartOfTokenColumn;
1176 if (Changes[i].StartOfBlockComment) {
1177 Shift = Changes[i].IndentationOffset +
1178 Changes[i].StartOfBlockComment->StartOfTokenColumn -
1179 Changes[i].StartOfTokenColumn;
1180 }
1181 if (Shift <= 0)
1182 continue;
1183
1184 setChangeSpaces(i, Changes[i].Spaces + Shift);
1185 }
1186}
1187
1188void WhitespaceManager::alignEscapedNewlines() {
1189 const auto Align = Style.AlignEscapedNewlines;
1190 if (Align == FormatStyle::ENAS_DontAlign)
1191 return;
1192
1193 const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
1194 const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
1195 const auto MaxColumn = Style.ColumnLimit;
1196 unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1197 unsigned StartOfMacro = 0;
1198 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
1199 Change &C = Changes[i];
1200 if (C.NewlinesBefore == 0 && (!WithLastLine || C.Tok->isNot(tok::eof)))
1201 continue;
1202 const bool InPPDirective = C.ContinuesPPDirective;
1203 const auto BackslashColumn = C.PreviousEndOfTokenColumn + 2;
1204 if (InPPDirective ||
1205 (WithLastLine && (MaxColumn == 0 || BackslashColumn <= MaxColumn))) {
1206 MaxEndOfLine = std::max(BackslashColumn, MaxEndOfLine);
1207 }
1208 if (!InPPDirective) {
1209 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1210 MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
1211 StartOfMacro = i;
1212 }
1213 }
1214 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1215}
1216
1217void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
1218 unsigned Column) {
1219 for (unsigned i = Start; i < End; ++i) {
1220 Change &C = Changes[i];
1221 if (C.NewlinesBefore > 0) {
1222 assert(C.ContinuesPPDirective);
1223 if (C.PreviousEndOfTokenColumn + 1 > Column)
1224 C.EscapedNewlineColumn = 0;
1225 else
1226 C.EscapedNewlineColumn = Column;
1227 }
1228 }
1229}
1230
1231void WhitespaceManager::alignArrayInitializers() {
1232 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1233 return;
1234
1235 for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1236 ChangeIndex < ChangeEnd; ++ChangeIndex) {
1237 auto &C = Changes[ChangeIndex];
1238 if (C.Tok->IsArrayInitializer) {
1239 bool FoundComplete = false;
1240 for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1241 ++InsideIndex) {
1242 const auto *Tok = Changes[InsideIndex].Tok;
1243 if (Tok->is(tok::pp_define))
1244 break;
1245 if (Tok == C.Tok->MatchingParen) {
1246 alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1247 ChangeIndex = InsideIndex + 1;
1248 FoundComplete = true;
1249 break;
1250 }
1251 }
1252 if (!FoundComplete)
1253 ChangeIndex = ChangeEnd;
1254 }
1255 }
1256}
1257
1258void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
1259
1260 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1261 alignArrayInitializersRightJustified(getCells(Start, End));
1262 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1263 alignArrayInitializersLeftJustified(getCells(Start, End));
1264}
1265
1266void WhitespaceManager::alignArrayInitializersRightJustified(
1267 CellDescriptions &&CellDescs) {
1268 if (!CellDescs.isRectangular())
1269 return;
1270
1271 const int BracePadding =
1272 Style.Cpp11BracedListStyle != FormatStyle::BLS_Block ? 0 : 1;
1273 auto &Cells = CellDescs.Cells;
1274 // Now go through and fixup the spaces.
1275 auto *CellIter = Cells.begin();
1276 for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1277 unsigned NetWidth = 0U;
1278 if (isSplitCell(*CellIter))
1279 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1280 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1281
1282 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1283 // So in here we want to see if there is a brace that falls
1284 // on a line that was split. If so on that line we make sure that
1285 // the spaces in front of the brace are enough.
1286 const auto *Next = CellIter;
1287 do {
1288 const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
1289 if (Previous && Previous->isNot(TT_LineComment)) {
1290 Changes[Next->Index].NewlinesBefore = 0;
1291 setChangeSpaces(Next->Index, BracePadding);
1292 }
1293 Next = Next->NextColumnElement;
1294 } while (Next);
1295 // Unless the array is empty, we need the position of all the
1296 // immediately adjacent cells
1297 if (CellIter != Cells.begin()) {
1298 auto ThisNetWidth =
1299 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1300 auto MaxNetWidth = getMaximumNetWidth(
1301 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1302 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1303 if (ThisNetWidth < MaxNetWidth)
1304 setChangeSpaces(CellIter->Index, MaxNetWidth - ThisNetWidth);
1305 auto RowCount = 1U;
1306 auto Offset = std::distance(Cells.begin(), CellIter);
1307 for (const auto *Next = CellIter->NextColumnElement; Next;
1308 Next = Next->NextColumnElement) {
1309 if (RowCount >= CellDescs.CellCounts.size())
1310 break;
1311 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1312 auto *End = Start + Offset;
1313 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1314 if (ThisNetWidth < MaxNetWidth)
1315 setChangeSpaces(Next->Index, MaxNetWidth - ThisNetWidth);
1316 ++RowCount;
1317 }
1318 }
1319 } else {
1320 auto ThisWidth =
1321 calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1322 NetWidth;
1323 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1324 int Spaces = (CellWidth - (ThisWidth + NetWidth));
1325 Spaces += (i > 0) ? 1 : BracePadding;
1326
1327 setChangeSpaces(CellIter->Index, Spaces);
1328 }
1329 alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1330 for (const auto *Next = CellIter->NextColumnElement; Next;
1331 Next = Next->NextColumnElement) {
1332 ThisWidth =
1333 calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1334 if (Changes[Next->Index].NewlinesBefore == 0) {
1335 int Spaces = (CellWidth - ThisWidth);
1336 Spaces += (i > 0) ? 1 : BracePadding;
1337
1338 setChangeSpaces(Next->Index, Spaces);
1339 }
1340 alignToStartOfCell(Next->Index, Next->EndIndex);
1341 }
1342 }
1343 }
1344}
1345
1346void WhitespaceManager::alignArrayInitializersLeftJustified(
1347 CellDescriptions &&CellDescs) {
1348
1349 if (!CellDescs.isRectangular())
1350 return;
1351
1352 const int BracePadding =
1353 Style.Cpp11BracedListStyle != FormatStyle::BLS_Block ? 0 : 1;
1354 auto &Cells = CellDescs.Cells;
1355 // Now go through and fixup the spaces.
1356 auto *CellIter = Cells.begin();
1357 // The first cell of every row needs to be against the left brace.
1358 for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
1359 auto &Change = Changes[Next->Index];
1360 int Spaces =
1361 Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
1362 setChangeSpaces(Next->Index, Spaces);
1363 }
1364 ++CellIter;
1365 for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1366 auto MaxNetWidth = getMaximumNetWidth(
1367 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1368 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1369 auto ThisNetWidth =
1370 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1371 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1372 int Spaces =
1373 MaxNetWidth - ThisNetWidth +
1374 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1
1375 : BracePadding);
1376 setChangeSpaces(CellIter->Index, Spaces);
1377 }
1378 auto RowCount = 1U;
1379 auto Offset = std::distance(Cells.begin(), CellIter);
1380 for (const auto *Next = CellIter->NextColumnElement; Next;
1381 Next = Next->NextColumnElement) {
1382 if (RowCount >= CellDescs.CellCounts.size())
1383 break;
1384 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1385 auto *End = Start + Offset;
1386 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1387 if (Changes[Next->Index].NewlinesBefore == 0) {
1388 int Spaces =
1389 MaxNetWidth - ThisNetWidth +
1390 (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : BracePadding);
1391 setChangeSpaces(Next->Index, Spaces);
1392 }
1393 ++RowCount;
1394 }
1395 }
1396}
1397
1398bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1399 if (Cell.HasSplit)
1400 return true;
1401 for (const auto *Next = Cell.NextColumnElement; Next;
1402 Next = Next->NextColumnElement) {
1403 if (Next->HasSplit)
1404 return true;
1405 }
1406 return false;
1407}
1408
1409WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1410 unsigned End) {
1411
1412 unsigned Depth = 0;
1413 unsigned Cell = 0;
1414 SmallVector<unsigned> CellCounts;
1415 unsigned InitialSpaces = 0;
1416 unsigned InitialTokenLength = 0;
1417 unsigned EndSpaces = 0;
1418 SmallVector<CellDescription> Cells;
1419 const FormatToken *MatchingParen = nullptr;
1420 for (unsigned i = Start; i < End; ++i) {
1421 auto &C = Changes[i];
1422 if (C.Tok->is(tok::l_brace))
1423 ++Depth;
1424 else if (C.Tok->is(tok::r_brace))
1425 --Depth;
1426 if (Depth == 2) {
1427 if (C.Tok->is(tok::l_brace)) {
1428 Cell = 0;
1429 MatchingParen = C.Tok->MatchingParen;
1430 if (InitialSpaces == 0) {
1431 InitialSpaces = C.Spaces + C.TokenLength;
1432 InitialTokenLength = C.TokenLength;
1433 auto j = i - 1;
1434 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1435 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1436 InitialTokenLength += Changes[j].TokenLength;
1437 }
1438 if (C.NewlinesBefore == 0) {
1439 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1440 InitialTokenLength += Changes[j].TokenLength;
1441 }
1442 }
1443 } else if (C.Tok->is(tok::comma)) {
1444 if (!Cells.empty())
1445 Cells.back().EndIndex = i;
1446 if (const auto *Next = C.Tok->getNextNonComment();
1447 Next && Next->isNot(tok::r_brace)) { // dangling comma
1448 ++Cell;
1449 }
1450 }
1451 } else if (Depth == 1) {
1452 if (C.Tok == MatchingParen) {
1453 if (!Cells.empty())
1454 Cells.back().EndIndex = i;
1455 Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1456 CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1457 : Cell);
1458 // Go to the next non-comment and ensure there is a break in front
1459 const auto *NextNonComment = C.Tok->getNextNonComment();
1460 while (NextNonComment && NextNonComment->is(tok::comma))
1461 NextNonComment = NextNonComment->getNextNonComment();
1462 auto j = i;
1463 while (j < End && Changes[j].Tok != NextNonComment)
1464 ++j;
1465 if (j < End && Changes[j].NewlinesBefore == 0 &&
1466 Changes[j].Tok->isNot(tok::r_brace)) {
1467 Changes[j].NewlinesBefore = 1;
1468 // Account for the added token lengths
1469 setChangeSpaces(j, InitialSpaces - InitialTokenLength);
1470 }
1471 } else if (C.Tok->is(tok::comment) && C.Tok->NewlinesBefore == 0) {
1472 // Trailing comments stay at a space past the last token
1473 setChangeSpaces(i, Changes[i - 1].Tok->is(tok::comma) ? 1 : 2);
1474 } else if (C.Tok->is(tok::l_brace)) {
1475 // We need to make sure that the ending braces is aligned to the
1476 // start of our initializer
1477 auto j = i - 1;
1478 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1479 ; // Nothing the loop does the work
1480 EndSpaces = Changes[j].Spaces;
1481 }
1482 } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1483 C.NewlinesBefore = 1;
1484 setChangeSpaces(i, EndSpaces);
1485 }
1486 if (C.Tok->StartsColumn) {
1487 // This gets us past tokens that have been split over multiple
1488 // lines
1489 bool HasSplit = false;
1490 if (Changes[i].NewlinesBefore > 0) {
1491 // So if we split a line previously and the tail line + this token is
1492 // less then the column limit we remove the split here and just put
1493 // the column start at a space past the comma
1494 //
1495 // FIXME This if branch covers the cases where the column is not
1496 // the first column. This leads to weird pathologies like the formatting
1497 // auto foo = Items{
1498 // Section{
1499 // 0, bar(),
1500 // }
1501 // };
1502 // Well if it doesn't lead to that it's indicative that the line
1503 // breaking should be revisited. Unfortunately alot of other options
1504 // interact with this
1505 auto j = i - 1;
1506 if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1507 Changes[j - 1].NewlinesBefore > 0) {
1508 --j;
1509 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1510 if (LineLimit < Style.ColumnLimit) {
1511 Changes[i].NewlinesBefore = 0;
1512 setChangeSpaces(i, 1);
1513 }
1514 }
1515 }
1516 while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1517 setChangeSpaces(i, InitialSpaces);
1518 ++i;
1519 HasSplit = true;
1520 }
1521 if (Changes[i].Tok != C.Tok)
1522 --i;
1523 Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1524 }
1525 }
1526
1527 return linkCells({Cells, CellCounts, InitialSpaces});
1528}
1529
1530unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1531 bool WithSpaces) const {
1532 unsigned CellWidth = 0;
1533 for (auto i = Start; i < End; i++) {
1534 if (Changes[i].NewlinesBefore > 0)
1535 CellWidth = 0;
1536 CellWidth += Changes[i].TokenLength;
1537 CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1538 }
1539 return CellWidth;
1540}
1541
1542void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1543 if ((End - Start) <= 1)
1544 return;
1545 // If the line is broken anywhere in there make sure everything
1546 // is aligned to the parent
1547 for (auto i = Start + 1; i < End; i++)
1548 if (Changes[i].NewlinesBefore > 0)
1549 setChangeSpaces(i, Changes[Start].Spaces);
1550}
1551
1552WhitespaceManager::CellDescriptions
1553WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1554 auto &Cells = CellDesc.Cells;
1555 for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1556 if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1557 for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1558 if (NextIter->Cell == CellIter->Cell) {
1559 CellIter->NextColumnElement = &(*NextIter);
1560 break;
1561 }
1562 }
1563 }
1564 }
1565 return std::move(CellDesc);
1566}
1567
1568void WhitespaceManager::setChangeSpaces(unsigned Start, unsigned Spaces) {
1569 SetChangeSpaces(Start, Spaces, Changes);
1570}
1571
1572void WhitespaceManager::generateChanges() {
1573 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1574 const Change &C = Changes[i];
1575 if (i > 0) {
1576 auto Last = Changes[i - 1].OriginalWhitespaceRange;
1577 auto New = Changes[i].OriginalWhitespaceRange;
1578 // Do not generate two replacements for the same location. As a special
1579 // case, it is allowed if there is a replacement for the empty range
1580 // between 2 tokens and another non-empty range at the start of the second
1581 // token. We didn't implement logic to combine replacements for 2
1582 // consecutive source ranges into a single replacement, because the
1583 // program works fine without it.
1584 //
1585 // We can't eliminate empty original whitespace ranges. They appear when
1586 // 2 tokens have no whitespace in between in the input. It does not
1587 // matter whether whitespace is to be added. If no whitespace is to be
1588 // added, the replacement will be empty, and it gets eliminated after this
1589 // step in storeReplacement. For example, if the input is `foo();`,
1590 // there will be a replacement for the range between every consecutive
1591 // pair of tokens.
1592 //
1593 // A replacement at the start of a token can be added by
1594 // BreakableStringLiteralUsingOperators::insertBreak when it adds braces
1595 // around the string literal. Say Verilog code is being formatted and the
1596 // first line is to become the next 2 lines.
1597 // x("long string");
1598 // x({"long ",
1599 // "string"});
1600 // There will be a replacement for the empty range between the parenthesis
1601 // and the string and another replacement for the quote character. The
1602 // replacement for the empty range between the parenthesis and the quote
1603 // comes from ContinuationIndenter::addTokenOnCurrentLine when it changes
1604 // the original empty range between the parenthesis and the string to
1605 // another empty one. The replacement for the quote character comes from
1606 // BreakableStringLiteralUsingOperators::insertBreak when it adds the
1607 // brace. In the example, the replacement for the empty range is the same
1608 // as the original text. However, eliminating replacements that are same
1609 // as the original does not help in general. For example, a newline can
1610 // be inserted, causing the first line to become the next 3 lines.
1611 // xxxxxxxxxxx("long string");
1612 // xxxxxxxxxxx(
1613 // {"long ",
1614 // "string"});
1615 // In that case, the empty range between the parenthesis and the string
1616 // will be replaced by a newline and 4 spaces. So we will still have to
1617 // deal with a replacement for an empty source range followed by a
1618 // replacement for a non-empty source range.
1619 if (Last.getBegin() == New.getBegin() &&
1620 (Last.getEnd() != Last.getBegin() ||
1621 New.getEnd() == New.getBegin())) {
1622 continue;
1623 }
1624 }
1625 if (C.CreateReplacement) {
1626 std::string ReplacementText = C.PreviousLinePostfix;
1627 if (C.ContinuesPPDirective) {
1628 appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1629 C.PreviousEndOfTokenColumn,
1630 C.EscapedNewlineColumn);
1631 } else {
1632 appendNewlineText(ReplacementText, C);
1633 }
1634 // FIXME: This assert should hold if we computed the column correctly.
1635 // assert((int)C.StartOfTokenColumn >= C.Spaces);
1636 unsigned IndentLevel = indentLevelFor(C);
1637 appendIndentText(ReplacementText, IndentLevel, std::max(0, C.Spaces),
1638 std::max((int)C.StartOfTokenColumn, C.Spaces) -
1639 std::max(0, C.Spaces),
1640 C.AlignedTo);
1641 C.Tok->AppliedIndentLevel =
1642 C.AlignedTo ? IndentLevel : std::max(0, C.Spaces) / Style.IndentWidth;
1643 ReplacementText.append(C.CurrentLinePrefix);
1644 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1645 }
1646 }
1647}
1648
1649void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1650 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1651 SourceMgr.getFileOffset(Range.getBegin());
1652 // Don't create a replacement, if it does not change anything.
1653 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1654 WhitespaceLength) == Text) {
1655 return;
1656 }
1657 auto Err = Replaces.add(tooling::Replacement(
1658 SourceMgr, CharSourceRange::getCharRange(Range), Text));
1659 // FIXME: better error handling. For now, just print an error message in the
1660 // release version.
1661 if (Err) {
1662 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1663 assert(false);
1664 }
1665}
1666
1667void WhitespaceManager::appendNewlineText(std::string &Text, const Change &C) {
1668 if (C.NewlinesBefore <= 0)
1669 return;
1670
1671 StringRef Newline = UseCRLF ? "\r\n" : "\n";
1672 Text.append(Newline);
1673
1674 if (C.Tok->HasFormFeedBefore)
1675 Text.append("\f");
1676
1677 for (unsigned I = 1; I < C.NewlinesBefore; ++I)
1678 Text.append(Newline);
1679}
1680
1681void WhitespaceManager::appendEscapedNewlineText(
1682 std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1683 unsigned EscapedNewlineColumn) {
1684 if (Newlines > 0) {
1685 unsigned Spaces =
1686 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1687 for (unsigned i = 0; i < Newlines; ++i) {
1688 Text.append(Spaces, ' ');
1689 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1690 Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1691 }
1692 }
1693}
1694
1695void WhitespaceManager::appendIndentText(std::string &Text,
1696 unsigned IndentLevel, unsigned Spaces,
1697 unsigned WhitespaceStartColumn,
1698 bool IsAligned) {
1699 switch (Style.UseTab) {
1701 Text.append(Spaces, ' ');
1702 break;
1704 if (Style.TabWidth) {
1705 unsigned FirstTabWidth =
1706 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1707
1708 // Insert only spaces when we want to end up before the next tab.
1709 if (Spaces < FirstTabWidth || Spaces == 1) {
1710 Text.append(Spaces, ' ');
1711 break;
1712 }
1713 // Align to the next tab.
1714 Spaces -= FirstTabWidth;
1715 Text.append("\t");
1716
1717 Text.append(Spaces / Style.TabWidth, '\t');
1718 Text.append(Spaces % Style.TabWidth, ' ');
1719 } else if (Spaces == 1) {
1720 Text.append(Spaces, ' ');
1721 }
1722 break;
1723 }
1725 if (WhitespaceStartColumn == 0) {
1726 unsigned Indentation = IndentLevel * Style.IndentWidth;
1727 Spaces = appendTabIndent(Text, Spaces, Indentation);
1728 }
1729 Text.append(Spaces, ' ');
1730 break;
1732 if (WhitespaceStartColumn == 0)
1733 Spaces = appendTabIndent(Text, Spaces, Spaces);
1734 Text.append(Spaces, ' ');
1735 break;
1737 if (WhitespaceStartColumn == 0) {
1738 unsigned Indentation =
1739 IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1740 Spaces = appendTabIndent(Text, Spaces, Indentation);
1741 }
1742 Text.append(Spaces, ' ');
1743 break;
1744 }
1745}
1746
1747unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1748 unsigned Indentation) {
1749 // This happens, e.g. when a line in a block comment is indented less than the
1750 // first one.
1751 if (Indentation > Spaces)
1752 Indentation = Spaces;
1753 if (Style.TabWidth) {
1754 unsigned Tabs = Indentation / Style.TabWidth;
1755 Text.append(Tabs, '\t');
1756 Spaces -= Tabs * Style.TabWidth;
1757 }
1758 return Spaces;
1759}
1760
1761} // namespace format
1762} // namespace clang
int Newlines
The number of newlines immediately before the Token after formatting.
FormatToken()
Token Tok
The Token.
unsigned NewlinesBefore
The number of newlines immediately before the Token.
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
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
Functor to sort changes in original source order.
bool operator()(const Change &C1, const Change &C2) const
void replaceWhitespaceInToken(const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars, StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective, unsigned Newlines, int Spaces)
Inserts or replaces whitespace in the middle of a token.
void addUntouchableToken(const FormatToken &Tok, bool InPPDirective)
Adds information about an unchangeable token's whitespace.
void replaceWhitespace(FormatToken &Tok, unsigned Newlines, unsigned Spaces, unsigned StartOfTokenColumn, const FormatToken *AlignedTo=nullptr, bool InPPDirective=false, unsigned IndentedFromColumn=0, bool CreateReplacement=true)
Replaces the whitespace in front of Tok.
static bool inputUsesCRLF(StringRef Text, bool DefaultToCRLF)
Infers whether the input is using CRLF.
llvm::Error addReplacement(const tooling::Replacement &Replacement)
const tooling::Replacements & generateReplacements()
Returns all the Replacements created during formatting.
A text replacement.
Definition Replacement.h:83
Maintains a set of replacements that are conflict-free.
#define INT_MAX
Definition limits.h:50
static void IncrementChangeSpaces(unsigned Start, int Delta, MutableArrayRef< WhitespaceManager::Change > Changes)
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
static const FormatToken & getLineStart(const FormatToken &Tok)
static void AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End, unsigned Column, bool RightJustify, ArrayRef< unsigned > Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes)
static void SetChangeSpaces(unsigned Start, unsigned Spaces, MutableArrayRef< WhitespaceManager::Change > Changes)
TokenType
Determines the semantic type of a syntactic token, e.g.
static unsigned AlignTokens(const FormatStyle &Style, F &&Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes, unsigned StartAt, const FormatStyle::AlignConsecutiveStyle &ACS={}, bool RightJustify=false)
static unsigned indentLevelFor(const WhitespaceManager::Change &C)
Top level wrappers for InstallAPI frontend operations.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
#define false
Definition stdbool.h:26
bool AcrossEmptyLines
Whether to align across empty lines.
Definition Format.h:178
bool Enabled
Whether aligning is enabled.
Definition Format.h:161
bool AcrossComments
Whether to align across comments.
Definition Format.h:191
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
@ UT_AlignWithSpaces
Use tabs for line continuation and indentation, and spaces for alignment.
Definition Format.h:6094
@ UT_ForContinuationAndIndentation
Fill all leading whitespace with tabs, and use spaces for alignment that appears within a line (e....
Definition Format.h:6091
@ UT_ForIndentation
Use tabs only for indentation.
Definition Format.h:6088
@ UT_Always
Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one.
Definition Format.h:6097
@ UT_Never
Never use tab.
Definition Format.h:6086
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition Format.h:579
@ TCAS_Leave
Leave trailing comments as they are.
Definition Format.h:561
@ TCAS_Always
Align trailing comments.
Definition Format.h:570
@ BLS_Block
Best suited for pre C++11 braced lists.
Definition Format.h:2918
@ AIAS_Left
Align array column and left justify the columns e.g.:
Definition Format.h:95
@ AIAS_Right
Align array column and right justify the columns e.g.:
Definition Format.h:105
@ AIAS_None
Don't align array initializer columns.
Definition Format.h:107
@ ENAS_DontAlign
Don't align escaped newlines.
Definition Format.h:480
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition Format.h:488
@ ENAS_LeftWithLastLine
Align escaped newlines as far left as possible, using the last line of the preprocessor directive as ...
Definition Format.h:497
@ PAS_Right
Align pointer to the right.
Definition Format.h:4542
@ RAS_Right
Align reference to the right.
Definition Format.h:4728
@ RAS_Pointer
Align reference like PointerAlignment.
Definition Format.h:4718
A wrapper around a Token storing information about the whitespace characters preceding it.
unsigned FakeRParens
Insert this many fake ) after this token for correct indentation.
SmallVector< prec::Level, 4 > FakeLParens
Stores the number of required fake parentheses and the corresponding operator precedence.
bool is(tok::TokenKind Kind) const
unsigned IndentLevel
The indent level of this token. Copied from the surrounding line.
unsigned AppliedIndentLevel
Block + continuation indent level, applied by the WhitespaceManager to this token.
FormatToken * Previous
The previous token in the unwrapped line.
Represents a change before a token, a break inside a token, or the layout of an unchanged token (or w...
Change(const FormatToken &Tok, bool CreateReplacement, SourceRange OriginalWhitespaceRange, int Spaces, unsigned StartOfTokenColumn, unsigned IndentedFromColumn, unsigned NewlinesBefore, StringRef PreviousLinePostfix, StringRef CurrentLinePrefix, const FormatToken *AlignedTo, bool ContinuesPPDirective, bool IsInsideToken)
Creates a Change.