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