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