clang 19.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(
32}
33
37 int Spaces, unsigned StartOfTokenColumn,
38 unsigned NewlinesBefore,
39 StringRef PreviousLinePostfix,
40 StringRef CurrentLinePrefix, bool IsAligned,
51}
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;
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.
238 if (Change.IsInsideToken && Change.NewlinesBefore == 0)
239 Change.IsTrailingComment = false;
240 Change.StartOfBlockComment = nullptr;
241 Change.IndentationOffset = 0;
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)) {
246 Change.IndentationOffset =
247 Change.StartOfTokenColumn -
248 Change.StartOfBlockComment->StartOfTokenColumn;
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 token for which Matches returns true is moved to this column.
283// RightJustify - Whether it is the token's right end or left end that gets
284// moved to that column.
285template <typename F>
286static void
287AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End,
288 unsigned Column, bool RightJustify, F &&Matches,
290 bool FoundMatchOnLine = false;
291 int Shift = 0;
292
293 // ScopeStack keeps track of the current scope depth. It contains indices of
294 // the first token on each scope.
295 // We only run the "Matches" function on tokens from the outer-most scope.
296 // However, we do need to pay special attention to one class of tokens
297 // that are not in the outer-most scope, and that is function parameters
298 // which are split across multiple lines, as illustrated by this example:
299 // double a(int x);
300 // int b(int y,
301 // double z);
302 // In the above example, we need to take special care to ensure that
303 // 'double z' is indented along with it's owning function 'b'.
304 // The same holds for calling a function:
305 // double a = foo(x);
306 // int b = bar(foo(y),
307 // foor(z));
308 // Similar for broken string literals:
309 // double x = 3.14;
310 // auto s = "Hello"
311 // "World";
312 // Special handling is required for 'nested' ternary operators.
313 SmallVector<unsigned, 16> ScopeStack;
314
315 for (unsigned i = Start; i != End; ++i) {
316 auto &CurrentChange = Changes[i];
317 if (ScopeStack.size() != 0 &&
318 CurrentChange.indentAndNestingLevel() <
319 Changes[ScopeStack.back()].indentAndNestingLevel()) {
320 ScopeStack.pop_back();
321 }
322
323 // Compare current token to previous non-comment token to ensure whether
324 // it is in a deeper scope or not.
325 unsigned PreviousNonComment = i - 1;
326 while (PreviousNonComment > Start &&
327 Changes[PreviousNonComment].Tok->is(tok::comment)) {
328 --PreviousNonComment;
329 }
330 if (i != Start && CurrentChange.indentAndNestingLevel() >
331 Changes[PreviousNonComment].indentAndNestingLevel()) {
332 ScopeStack.push_back(i);
333 }
334
335 bool InsideNestedScope = ScopeStack.size() != 0;
336 bool ContinuedStringLiteral = i > Start &&
337 CurrentChange.Tok->is(tok::string_literal) &&
338 Changes[i - 1].Tok->is(tok::string_literal);
339 bool SkipMatchCheck = InsideNestedScope || ContinuedStringLiteral;
340
341 if (CurrentChange.NewlinesBefore > 0 && !SkipMatchCheck) {
342 Shift = 0;
343 FoundMatchOnLine = false;
344 }
345
346 // If this is the first matching token to be aligned, remember by how many
347 // spaces it has to be shifted, so the rest of the changes on the line are
348 // shifted by the same amount
349 if (!FoundMatchOnLine && !SkipMatchCheck && Matches(CurrentChange)) {
350 FoundMatchOnLine = true;
351 Shift = Column - (RightJustify ? CurrentChange.TokenLength : 0) -
352 CurrentChange.StartOfTokenColumn;
353 CurrentChange.Spaces += Shift;
354 // FIXME: This is a workaround that should be removed when we fix
355 // http://llvm.org/PR53699. An assertion later below verifies this.
356 if (CurrentChange.NewlinesBefore == 0) {
357 CurrentChange.Spaces =
358 std::max(CurrentChange.Spaces,
359 static_cast<int>(CurrentChange.Tok->SpacesRequiredBefore));
360 }
361 }
362
363 if (Shift == 0)
364 continue;
365
366 // This is for function parameters that are split across multiple lines,
367 // as mentioned in the ScopeStack comment.
368 if (InsideNestedScope && CurrentChange.NewlinesBefore > 0) {
369 unsigned ScopeStart = ScopeStack.back();
370 auto ShouldShiftBeAdded = [&] {
371 // Function declaration
372 if (Changes[ScopeStart - 1].Tok->is(TT_FunctionDeclarationName))
373 return true;
374
375 // Lambda.
376 if (Changes[ScopeStart - 1].Tok->is(TT_LambdaLBrace))
377 return false;
378
379 // Continued function declaration
380 if (ScopeStart > Start + 1 &&
381 Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) {
382 return true;
383 }
384
385 // Continued (template) function call.
386 if (ScopeStart > Start + 1 &&
387 Changes[ScopeStart - 2].Tok->isOneOf(tok::identifier,
388 TT_TemplateCloser) &&
389 Changes[ScopeStart - 1].Tok->is(tok::l_paren) &&
390 Changes[ScopeStart].Tok->isNot(TT_LambdaLSquare)) {
391 if (CurrentChange.Tok->MatchingParen &&
392 CurrentChange.Tok->MatchingParen->is(TT_LambdaLBrace)) {
393 return false;
394 }
395 if (Changes[ScopeStart].NewlinesBefore > 0)
396 return false;
397 if (CurrentChange.Tok->is(tok::l_brace) &&
398 CurrentChange.Tok->is(BK_BracedInit)) {
399 return true;
400 }
401 return Style.BinPackArguments;
402 }
403
404 // Ternary operator
405 if (CurrentChange.Tok->is(TT_ConditionalExpr))
406 return true;
407
408 // Period Initializer .XXX = 1.
409 if (CurrentChange.Tok->is(TT_DesignatedInitializerPeriod))
410 return true;
411
412 // Continued ternary operator
413 if (CurrentChange.Tok->Previous &&
414 CurrentChange.Tok->Previous->is(TT_ConditionalExpr)) {
415 return true;
416 }
417
418 // Continued direct-list-initialization using braced list.
419 if (ScopeStart > Start + 1 &&
420 Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
421 Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
422 CurrentChange.Tok->is(tok::l_brace) &&
423 CurrentChange.Tok->is(BK_BracedInit)) {
424 return true;
425 }
426
427 // Continued braced list.
428 if (ScopeStart > Start + 1 &&
429 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&
430 Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
431 CurrentChange.Tok->isNot(tok::r_brace)) {
432 for (unsigned OuterScopeStart : llvm::reverse(ScopeStack)) {
433 // Lambda.
434 if (OuterScopeStart > Start &&
435 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) {
436 return false;
437 }
438 }
439 if (Changes[ScopeStart].NewlinesBefore > 0)
440 return false;
441 return true;
442 }
443
444 // Continued template parameter.
445 if (Changes[ScopeStart - 1].Tok->is(TT_TemplateOpener))
446 return true;
447
448 return false;
449 };
450
451 if (ShouldShiftBeAdded())
452 CurrentChange.Spaces += Shift;
453 }
454
455 if (ContinuedStringLiteral)
456 CurrentChange.Spaces += Shift;
457
458 // We should not remove required spaces unless we break the line before.
459 assert(Shift > 0 || Changes[i].NewlinesBefore > 0 ||
460 CurrentChange.Spaces >=
461 static_cast<int>(Changes[i].Tok->SpacesRequiredBefore) ||
462 CurrentChange.Tok->is(tok::eof));
463
464 CurrentChange.StartOfTokenColumn += Shift;
465 if (i + 1 != Changes.size())
466 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
467
468 // If PointerAlignment is PAS_Right, keep *s or &s next to the token,
469 // except if the token is equal, then a space is needed.
470 if ((Style.PointerAlignment == FormatStyle::PAS_Right ||
471 Style.ReferenceAlignment == FormatStyle::RAS_Right) &&
472 CurrentChange.Spaces != 0 && CurrentChange.Tok->isNot(tok::equal)) {
473 const bool ReferenceNotRightAligned =
474 Style.ReferenceAlignment != FormatStyle::RAS_Right &&
475 Style.ReferenceAlignment != FormatStyle::RAS_Pointer;
476 for (int Previous = i - 1;
477 Previous >= 0 && Changes[Previous].Tok->is(TT_PointerOrReference);
478 --Previous) {
479 assert(Changes[Previous].Tok->isPointerOrReference());
480 if (Changes[Previous].Tok->isNot(tok::star)) {
481 if (ReferenceNotRightAligned)
482 continue;
483 } else if (Style.PointerAlignment != FormatStyle::PAS_Right) {
484 continue;
485 }
486 Changes[Previous + 1].Spaces -= Shift;
487 Changes[Previous].Spaces += Shift;
488 Changes[Previous].StartOfTokenColumn += Shift;
489 }
490 }
491 }
492}
493
494// Walk through a subset of the changes, starting at StartAt, and find
495// sequences of matching tokens to align. To do so, keep track of the lines and
496// whether or not a matching token was found on a line. If a matching token is
497// found, extend the current sequence. If the current line cannot be part of a
498// sequence, e.g. because there is an empty line before it or it contains only
499// non-matching tokens, finalize the previous sequence.
500// The value returned is the token on which we stopped, either because we
501// exhausted all items inside Changes, or because we hit a scope level higher
502// than our initial scope.
503// This function is recursive. Each invocation processes only the scope level
504// equal to the initial level, which is the level of Changes[StartAt].
505// If we encounter a scope level greater than the initial level, then we call
506// ourselves recursively, thereby avoiding the pollution of the current state
507// with the alignment requirements of the nested sub-level. This recursive
508// behavior is necessary for aligning function prototypes that have one or more
509// arguments.
510// If this function encounters a scope level less than the initial level,
511// it returns the current position.
512// There is a non-obvious subtlety in the recursive behavior: Even though we
513// defer processing of nested levels to recursive invocations of this
514// function, when it comes time to align a sequence of tokens, we run the
515// alignment on the entire sequence, including the nested levels.
516// When doing so, most of the nested tokens are skipped, because their
517// alignment was already handled by the recursive invocations of this function.
518// However, the special exception is that we do NOT skip function parameters
519// that are split across multiple lines. See the test case in FormatTest.cpp
520// that mentions "split function parameter alignment" for an example of this.
521// When the parameter RightJustify is true, the operator will be
522// right-justified. It is used to align compound assignments like `+=` and `=`.
523// When RightJustify and ACS.PadOperators are true, operators in each block to
524// be aligned will be padded on the left to the same length before aligning.
525template <typename F>
526static unsigned AlignTokens(const FormatStyle &Style, F &&Matches,
528 unsigned StartAt,
530 bool RightJustify = false) {
531 // We arrange each line in 3 parts. The operator to be aligned (the anchor),
532 // and text to its left and right. In the aligned text the width of each part
533 // will be the maximum of that over the block that has been aligned. Maximum
534 // widths of each part so far. When RightJustify is true and ACS.PadOperators
535 // is false, the part from start of line to the right end of the anchor.
536 // Otherwise, only the part to the left of the anchor. Including the space
537 // that exists on its left from the start. Not including the padding added on
538 // the left to right-justify the anchor.
539 unsigned WidthLeft = 0;
540 // The operator to be aligned when RightJustify is true and ACS.PadOperators
541 // is false. 0 otherwise.
542 unsigned WidthAnchor = 0;
543 // Width to the right of the anchor. Plus width of the anchor when
544 // RightJustify is false.
545 unsigned WidthRight = 0;
546
547 // Line number of the start and the end of the current token sequence.
548 unsigned StartOfSequence = 0;
549 unsigned EndOfSequence = 0;
550
551 // Measure the scope level (i.e. depth of (), [], {}) of the first token, and
552 // abort when we hit any token in a higher scope than the starting one.
553 auto IndentAndNestingLevel = StartAt < Changes.size()
554 ? Changes[StartAt].indentAndNestingLevel()
555 : std::tuple<unsigned, unsigned, unsigned>();
556
557 // Keep track of the number of commas before the matching tokens, we will only
558 // align a sequence of matching tokens if they are preceded by the same number
559 // of commas.
560 unsigned CommasBeforeLastMatch = 0;
561 unsigned CommasBeforeMatch = 0;
562
563 // Whether a matching token has been found on the current line.
564 bool FoundMatchOnLine = false;
565
566 // Whether the current line consists purely of comments.
567 bool LineIsComment = true;
568
569 // Aligns a sequence of matching tokens, on the MinColumn column.
570 //
571 // Sequences start from the first matching token to align, and end at the
572 // first token of the first line that doesn't need to be aligned.
573 //
574 // We need to adjust the StartOfTokenColumn of each Change that is on a line
575 // containing any matching token to be aligned and located after such token.
576 auto AlignCurrentSequence = [&] {
577 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
578 AlignTokenSequence(Style, StartOfSequence, EndOfSequence,
579 WidthLeft + WidthAnchor, RightJustify, Matches,
580 Changes);
581 }
582 WidthLeft = 0;
583 WidthAnchor = 0;
584 WidthRight = 0;
585 StartOfSequence = 0;
586 EndOfSequence = 0;
587 };
588
589 unsigned i = StartAt;
590 for (unsigned e = Changes.size(); i != e; ++i) {
591 auto &CurrentChange = Changes[i];
592 if (CurrentChange.indentAndNestingLevel() < IndentAndNestingLevel)
593 break;
594
595 if (CurrentChange.NewlinesBefore != 0) {
596 CommasBeforeMatch = 0;
597 EndOfSequence = i;
598
599 // Whether to break the alignment sequence because of an empty line.
600 bool EmptyLineBreak =
601 (CurrentChange.NewlinesBefore > 1) && !ACS.AcrossEmptyLines;
602
603 // Whether to break the alignment sequence because of a line without a
604 // match.
605 bool NoMatchBreak =
606 !FoundMatchOnLine && !(LineIsComment && ACS.AcrossComments);
607
608 if (EmptyLineBreak || NoMatchBreak)
609 AlignCurrentSequence();
610
611 // A new line starts, re-initialize line status tracking bools.
612 // Keep the match state if a string literal is continued on this line.
613 if (i == 0 || CurrentChange.Tok->isNot(tok::string_literal) ||
614 Changes[i - 1].Tok->isNot(tok::string_literal)) {
615 FoundMatchOnLine = false;
616 }
617 LineIsComment = true;
618 }
619
620 if (CurrentChange.Tok->isNot(tok::comment))
621 LineIsComment = false;
622
623 if (CurrentChange.Tok->is(tok::comma)) {
624 ++CommasBeforeMatch;
625 } else if (CurrentChange.indentAndNestingLevel() > IndentAndNestingLevel) {
626 // Call AlignTokens recursively, skipping over this scope block.
627 unsigned StoppedAt =
628 AlignTokens(Style, Matches, Changes, i, ACS, RightJustify);
629 i = StoppedAt - 1;
630 continue;
631 }
632
633 if (!Matches(CurrentChange))
634 continue;
635
636 // If there is more than one matching token per line, or if the number of
637 // preceding commas, do not match anymore, end the sequence.
638 if (FoundMatchOnLine || CommasBeforeMatch != CommasBeforeLastMatch)
639 AlignCurrentSequence();
640
641 CommasBeforeLastMatch = CommasBeforeMatch;
642 FoundMatchOnLine = true;
643
644 if (StartOfSequence == 0)
645 StartOfSequence = i;
646
647 unsigned ChangeWidthLeft = CurrentChange.StartOfTokenColumn;
648 unsigned ChangeWidthAnchor = 0;
649 unsigned ChangeWidthRight = 0;
650 if (RightJustify)
651 if (ACS.PadOperators)
652 ChangeWidthAnchor = CurrentChange.TokenLength;
653 else
654 ChangeWidthLeft += CurrentChange.TokenLength;
655 else
656 ChangeWidthRight = CurrentChange.TokenLength;
657 for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) {
658 ChangeWidthRight += Changes[j].Spaces;
659 // Changes are generally 1:1 with the tokens, but a change could also be
660 // inside of a token, in which case it's counted more than once: once for
661 // the whitespace surrounding the token (!IsInsideToken) and once for
662 // each whitespace change within it (IsInsideToken).
663 // Therefore, changes inside of a token should only count the space.
664 if (!Changes[j].IsInsideToken)
665 ChangeWidthRight += Changes[j].TokenLength;
666 }
667
668 // If we are restricted by the maximum column width, end the sequence.
669 unsigned NewLeft = std::max(ChangeWidthLeft, WidthLeft);
670 unsigned NewAnchor = std::max(ChangeWidthAnchor, WidthAnchor);
671 unsigned NewRight = std::max(ChangeWidthRight, WidthRight);
672 // `ColumnLimit == 0` means there is no column limit.
673 if (Style.ColumnLimit != 0 &&
674 Style.ColumnLimit < NewLeft + NewAnchor + NewRight) {
675 AlignCurrentSequence();
676 StartOfSequence = i;
677 WidthLeft = ChangeWidthLeft;
678 WidthAnchor = ChangeWidthAnchor;
679 WidthRight = ChangeWidthRight;
680 } else {
681 WidthLeft = NewLeft;
682 WidthAnchor = NewAnchor;
683 WidthRight = NewRight;
684 }
685 }
686
687 EndOfSequence = i;
688 AlignCurrentSequence();
689 return i;
690}
691
692// Aligns a sequence of matching tokens, on the MinColumn column.
693//
694// Sequences start from the first matching token to align, and end at the
695// first token of the first line that doesn't need to be aligned.
696//
697// We need to adjust the StartOfTokenColumn of each Change that is on a line
698// containing any matching token to be aligned and located after such token.
700 unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn,
701 std::function<bool(const WhitespaceManager::Change &C)> Matches,
703 if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) {
704 bool FoundMatchOnLine = false;
705 int Shift = 0;
706
707 for (unsigned I = StartOfSequence; I != EndOfSequence; ++I) {
708 if (Changes[I].NewlinesBefore > 0) {
709 Shift = 0;
710 FoundMatchOnLine = false;
711 }
712
713 // If this is the first matching token to be aligned, remember by how many
714 // spaces it has to be shifted, so the rest of the changes on the line are
715 // shifted by the same amount.
716 if (!FoundMatchOnLine && Matches(Changes[I])) {
717 FoundMatchOnLine = true;
718 Shift = MinColumn - Changes[I].StartOfTokenColumn;
719 Changes[I].Spaces += Shift;
720 }
721
722 assert(Shift >= 0);
723 Changes[I].StartOfTokenColumn += Shift;
724 if (I + 1 != Changes.size())
725 Changes[I + 1].PreviousEndOfTokenColumn += Shift;
726 }
727 }
728
729 MinColumn = 0;
730 StartOfSequence = 0;
731 EndOfSequence = 0;
732}
733
734void WhitespaceManager::alignConsecutiveMacros() {
735 if (!Style.AlignConsecutiveMacros.Enabled)
736 return;
737
738 auto AlignMacrosMatches = [](const Change &C) {
739 const FormatToken *Current = C.Tok;
740 unsigned SpacesRequiredBefore = 1;
741
742 if (Current->SpacesRequiredBefore == 0 || !Current->Previous)
743 return false;
744
745 Current = Current->Previous;
746
747 // If token is a ")", skip over the parameter list, to the
748 // token that precedes the "("
749 if (Current->is(tok::r_paren) && Current->MatchingParen) {
750 Current = Current->MatchingParen->Previous;
751 SpacesRequiredBefore = 0;
752 }
753
754 if (!Current || Current->isNot(tok::identifier))
755 return false;
756
757 if (!Current->Previous || Current->Previous->isNot(tok::pp_define))
758 return false;
759
760 // For a macro function, 0 spaces are required between the
761 // identifier and the lparen that opens the parameter list.
762 // For a simple macro, 1 space is required between the
763 // identifier and the first token of the defined value.
764 return Current->Next->SpacesRequiredBefore == SpacesRequiredBefore;
765 };
766
767 unsigned MinColumn = 0;
768
769 // Start and end of the token sequence we're processing.
770 unsigned StartOfSequence = 0;
771 unsigned EndOfSequence = 0;
772
773 // Whether a matching token has been found on the current line.
774 bool FoundMatchOnLine = false;
775
776 // Whether the current line consists only of comments
777 bool LineIsComment = true;
778
779 unsigned I = 0;
780 for (unsigned E = Changes.size(); I != E; ++I) {
781 if (Changes[I].NewlinesBefore != 0) {
782 EndOfSequence = I;
783
784 // Whether to break the alignment sequence because of an empty line.
785 bool EmptyLineBreak = (Changes[I].NewlinesBefore > 1) &&
786 !Style.AlignConsecutiveMacros.AcrossEmptyLines;
787
788 // Whether to break the alignment sequence because of a line without a
789 // match.
790 bool NoMatchBreak =
791 !FoundMatchOnLine &&
792 !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments);
793
794 if (EmptyLineBreak || NoMatchBreak) {
795 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
796 AlignMacrosMatches, Changes);
797 }
798
799 // A new line starts, re-initialize line status tracking bools.
800 FoundMatchOnLine = false;
801 LineIsComment = true;
802 }
803
804 if (Changes[I].Tok->isNot(tok::comment))
805 LineIsComment = false;
806
807 if (!AlignMacrosMatches(Changes[I]))
808 continue;
809
810 FoundMatchOnLine = true;
811
812 if (StartOfSequence == 0)
813 StartOfSequence = I;
814
815 unsigned ChangeMinColumn = Changes[I].StartOfTokenColumn;
816 MinColumn = std::max(MinColumn, ChangeMinColumn);
817 }
818
819 EndOfSequence = I;
820 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
821 AlignMacrosMatches, Changes);
822}
823
824void WhitespaceManager::alignConsecutiveAssignments() {
825 if (!Style.AlignConsecutiveAssignments.Enabled)
826 return;
827
829 Style,
830 [&](const Change &C) {
831 // Do not align on equal signs that are first on a line.
832 if (C.NewlinesBefore > 0)
833 return false;
834
835 // Do not align on equal signs that are last on a line.
836 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
837 return false;
838
839 // Do not align operator= overloads.
840 FormatToken *Previous = C.Tok->getPreviousNonComment();
841 if (Previous && Previous->is(tok::kw_operator))
842 return false;
843
844 return Style.AlignConsecutiveAssignments.AlignCompound
845 ? C.Tok->getPrecedence() == prec::Assignment
846 : (C.Tok->is(tok::equal) ||
847 // In Verilog the '<=' is not a compound assignment, thus
848 // it is aligned even when the AlignCompound option is not
849 // set.
850 (Style.isVerilog() && C.Tok->is(tok::lessequal) &&
851 C.Tok->getPrecedence() == prec::Assignment));
852 },
853 Changes, /*StartAt=*/0, Style.AlignConsecutiveAssignments,
854 /*RightJustify=*/true);
855}
856
857void WhitespaceManager::alignConsecutiveBitFields() {
858 alignConsecutiveColons(Style.AlignConsecutiveBitFields, TT_BitFieldColon);
859}
860
861void WhitespaceManager::alignConsecutiveColons(
862 const FormatStyle::AlignConsecutiveStyle &AlignStyle, TokenType Type) {
863 if (!AlignStyle.Enabled)
864 return;
865
867 Style,
868 [&](Change const &C) {
869 // Do not align on ':' that is first on a line.
870 if (C.NewlinesBefore > 0)
871 return false;
872
873 // Do not align on ':' that is last on a line.
874 if (&C != &Changes.back() && (&C + 1)->NewlinesBefore > 0)
875 return false;
876
877 return C.Tok->is(Type);
878 },
879 Changes, /*StartAt=*/0, AlignStyle);
880}
881
882void WhitespaceManager::alignConsecutiveShortCaseStatements(bool IsExpr) {
883 if (!Style.AlignConsecutiveShortCaseStatements.Enabled ||
884 !(IsExpr ? Style.AllowShortCaseExpressionOnASingleLine
885 : Style.AllowShortCaseLabelsOnASingleLine)) {
886 return;
887 }
888
889 const auto Type = IsExpr ? TT_CaseLabelArrow : TT_CaseLabelColon;
890 const auto &Option = Style.AlignConsecutiveShortCaseStatements;
891 const bool AlignArrowOrColon =
892 IsExpr ? Option.AlignCaseArrows : Option.AlignCaseColons;
893
894 auto Matches = [&](const Change &C) {
895 if (AlignArrowOrColon)
896 return C.Tok->is(Type);
897
898 // Ignore 'IsInsideToken' to allow matching trailing comments which
899 // need to be reflowed as that causes the token to appear in two
900 // different changes, which will cause incorrect alignment as we'll
901 // reflow early due to detecting multiple aligning tokens per line.
902 return !C.IsInsideToken && C.Tok->Previous && C.Tok->Previous->is(Type);
903 };
904
905 unsigned MinColumn = 0;
906
907 // Empty case statements don't break the alignment, but don't necessarily
908 // match our predicate, so we need to track their column so they can push out
909 // our alignment.
910 unsigned MinEmptyCaseColumn = 0;
911
912 // Start and end of the token sequence we're processing.
913 unsigned StartOfSequence = 0;
914 unsigned EndOfSequence = 0;
915
916 // Whether a matching token has been found on the current line.
917 bool FoundMatchOnLine = false;
918
919 bool LineIsComment = true;
920 bool LineIsEmptyCase = false;
921
922 unsigned I = 0;
923 for (unsigned E = Changes.size(); I != E; ++I) {
924 if (Changes[I].NewlinesBefore != 0) {
925 // Whether to break the alignment sequence because of an empty line.
926 bool EmptyLineBreak =
927 (Changes[I].NewlinesBefore > 1) &&
928 !Style.AlignConsecutiveShortCaseStatements.AcrossEmptyLines;
929
930 // Whether to break the alignment sequence because of a line without a
931 // match.
932 bool NoMatchBreak =
933 !FoundMatchOnLine &&
934 !(LineIsComment &&
935 Style.AlignConsecutiveShortCaseStatements.AcrossComments) &&
936 !LineIsEmptyCase;
937
938 if (EmptyLineBreak || NoMatchBreak) {
939 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn,
940 Matches, Changes);
941 MinEmptyCaseColumn = 0;
942 }
943
944 // A new line starts, re-initialize line status tracking bools.
945 FoundMatchOnLine = false;
946 LineIsComment = true;
947 LineIsEmptyCase = false;
948 }
949
950 if (Changes[I].Tok->isNot(tok::comment))
951 LineIsComment = false;
952
953 if (Changes[I].Tok->is(Type)) {
954 LineIsEmptyCase =
955 !Changes[I].Tok->Next || Changes[I].Tok->Next->isTrailingComment();
956
957 if (LineIsEmptyCase) {
958 if (Style.AlignConsecutiveShortCaseStatements.AlignCaseColons) {
959 MinEmptyCaseColumn =
960 std::max(MinEmptyCaseColumn, Changes[I].StartOfTokenColumn);
961 } else {
962 MinEmptyCaseColumn =
963 std::max(MinEmptyCaseColumn, Changes[I].StartOfTokenColumn + 2);
964 }
965 }
966 }
967
968 if (!Matches(Changes[I]))
969 continue;
970
971 if (LineIsEmptyCase)
972 continue;
973
974 FoundMatchOnLine = true;
975
976 if (StartOfSequence == 0)
977 StartOfSequence = I;
978
979 EndOfSequence = I + 1;
980
981 MinColumn = std::max(MinColumn, Changes[I].StartOfTokenColumn);
982
983 // Allow empty case statements to push out our alignment.
984 MinColumn = std::max(MinColumn, MinEmptyCaseColumn);
985 }
986
987 AlignMatchingTokenSequence(StartOfSequence, EndOfSequence, MinColumn, Matches,
988 Changes);
989}
990
991void WhitespaceManager::alignConsecutiveTableGenBreakingDAGArgColons() {
992 alignConsecutiveColons(Style.AlignConsecutiveTableGenBreakingDAGArgColons,
993 TT_TableGenDAGArgListColonToAlign);
994}
995
996void WhitespaceManager::alignConsecutiveTableGenCondOperatorColons() {
997 alignConsecutiveColons(Style.AlignConsecutiveTableGenCondOperatorColons,
998 TT_TableGenCondOperatorColon);
999}
1000
1001void WhitespaceManager::alignConsecutiveTableGenDefinitions() {
1002 alignConsecutiveColons(Style.AlignConsecutiveTableGenDefinitionColons,
1003 TT_InheritanceColon);
1004}
1005
1006void WhitespaceManager::alignConsecutiveDeclarations() {
1007 if (!Style.AlignConsecutiveDeclarations.Enabled)
1008 return;
1009
1011 Style,
1012 [&](Change const &C) {
1013 if (Style.AlignConsecutiveDeclarations.AlignFunctionPointers) {
1014 for (const auto *Prev = C.Tok->Previous; Prev; Prev = Prev->Previous)
1015 if (Prev->is(tok::equal))
1016 return false;
1017 if (C.Tok->is(TT_FunctionTypeLParen))
1018 return true;
1019 }
1020 if (C.Tok->is(TT_FunctionDeclarationName))
1021 return true;
1022 if (C.Tok->isNot(TT_StartOfName))
1023 return false;
1024 if (C.Tok->Previous &&
1025 C.Tok->Previous->is(TT_StatementAttributeLikeMacro))
1026 return false;
1027 // Check if there is a subsequent name that starts the same declaration.
1028 for (FormatToken *Next = C.Tok->Next; Next; Next = Next->Next) {
1029 if (Next->is(tok::comment))
1030 continue;
1031 if (Next->is(TT_PointerOrReference))
1032 return false;
1033 if (!Next->Tok.getIdentifierInfo())
1034 break;
1035 if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName,
1036 tok::kw_operator)) {
1037 return false;
1038 }
1039 }
1040 return true;
1041 },
1042 Changes, /*StartAt=*/0, Style.AlignConsecutiveDeclarations);
1043}
1044
1045void WhitespaceManager::alignChainedConditionals() {
1046 if (Style.BreakBeforeTernaryOperators) {
1048 Style,
1049 [](Change const &C) {
1050 // Align question operators and last colon
1051 return C.Tok->is(TT_ConditionalExpr) &&
1052 ((C.Tok->is(tok::question) && !C.NewlinesBefore) ||
1053 (C.Tok->is(tok::colon) && C.Tok->Next &&
1054 (C.Tok->Next->FakeLParens.size() == 0 ||
1055 C.Tok->Next->FakeLParens.back() != prec::Conditional)));
1056 },
1057 Changes, /*StartAt=*/0);
1058 } else {
1059 static auto AlignWrappedOperand = [](Change const &C) {
1060 FormatToken *Previous = C.Tok->getPreviousNonComment();
1061 return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) &&
1062 (Previous->is(tok::colon) &&
1063 (C.Tok->FakeLParens.size() == 0 ||
1064 C.Tok->FakeLParens.back() != prec::Conditional));
1065 };
1066 // Ensure we keep alignment of wrapped operands with non-wrapped operands
1067 // Since we actually align the operators, the wrapped operands need the
1068 // extra offset to be properly aligned.
1069 for (Change &C : Changes)
1070 if (AlignWrappedOperand(C))
1071 C.StartOfTokenColumn -= 2;
1073 Style,
1074 [this](Change const &C) {
1075 // Align question operators if next operand is not wrapped, as
1076 // well as wrapped operands after question operator or last
1077 // colon in conditional sequence
1078 return (C.Tok->is(TT_ConditionalExpr) && C.Tok->is(tok::question) &&
1079 &C != &Changes.back() && (&C + 1)->NewlinesBefore == 0 &&
1080 !(&C + 1)->IsTrailingComment) ||
1081 AlignWrappedOperand(C);
1082 },
1083 Changes, /*StartAt=*/0);
1084 }
1085}
1086
1087void WhitespaceManager::alignTrailingComments() {
1088 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
1089 return;
1090
1091 const int Size = Changes.size();
1092 int MinColumn = 0;
1093 int StartOfSequence = 0;
1094 bool BreakBeforeNext = false;
1095 int NewLineThreshold = 1;
1096 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Always)
1097 NewLineThreshold = Style.AlignTrailingComments.OverEmptyLines + 1;
1098
1099 for (int I = 0, MaxColumn = INT_MAX, Newlines = 0; I < Size; ++I) {
1100 auto &C = Changes[I];
1101 if (C.StartOfBlockComment)
1102 continue;
1103 Newlines += C.NewlinesBefore;
1104 if (!C.IsTrailingComment)
1105 continue;
1106
1107 if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Leave) {
1108 const int OriginalSpaces =
1109 C.OriginalWhitespaceRange.getEnd().getRawEncoding() -
1110 C.OriginalWhitespaceRange.getBegin().getRawEncoding() -
1111 C.Tok->LastNewlineOffset;
1112 assert(OriginalSpaces >= 0);
1113 const auto RestoredLineLength =
1114 C.StartOfTokenColumn + C.TokenLength + OriginalSpaces;
1115 // If leaving comments makes the line exceed the column limit, give up to
1116 // leave the comments.
1117 if (RestoredLineLength >= Style.ColumnLimit && Style.ColumnLimit > 0)
1118 break;
1119 C.Spaces = OriginalSpaces;
1120 continue;
1121 }
1122
1123 const int ChangeMinColumn = C.StartOfTokenColumn;
1124 int ChangeMaxColumn;
1125
1126 // If we don't create a replacement for this change, we have to consider
1127 // it to be immovable.
1128 if (!C.CreateReplacement)
1129 ChangeMaxColumn = ChangeMinColumn;
1130 else if (Style.ColumnLimit == 0)
1131 ChangeMaxColumn = INT_MAX;
1132 else if (Style.ColumnLimit >= C.TokenLength)
1133 ChangeMaxColumn = Style.ColumnLimit - C.TokenLength;
1134 else
1135 ChangeMaxColumn = ChangeMinColumn;
1136
1137 if (I + 1 < Size && Changes[I + 1].ContinuesPPDirective &&
1138 ChangeMaxColumn >= 2) {
1139 ChangeMaxColumn -= 2;
1140 }
1141
1142 bool WasAlignedWithStartOfNextLine = false;
1143 if (C.NewlinesBefore >= 1) { // A comment on its own line.
1144 const auto CommentColumn =
1145 SourceMgr.getSpellingColumnNumber(C.OriginalWhitespaceRange.getEnd());
1146 for (int J = I + 1; J < Size; ++J) {
1147 if (Changes[J].Tok->is(tok::comment))
1148 continue;
1149
1150 const auto NextColumn = SourceMgr.getSpellingColumnNumber(
1151 Changes[J].OriginalWhitespaceRange.getEnd());
1152 // The start of the next token was previously aligned with the
1153 // start of this comment.
1154 WasAlignedWithStartOfNextLine =
1155 CommentColumn == NextColumn ||
1156 CommentColumn == NextColumn + Style.IndentWidth;
1157 break;
1158 }
1159 }
1160
1161 // We don't want to align comments which end a scope, which are here
1162 // identified by most closing braces.
1163 auto DontAlignThisComment = [](const auto *Tok) {
1164 if (Tok->is(tok::semi)) {
1165 Tok = Tok->getPreviousNonComment();
1166 if (!Tok)
1167 return false;
1168 }
1169 if (Tok->is(tok::r_paren)) {
1170 // Back up past the parentheses and a `TT_DoWhile` that may precede.
1171 Tok = Tok->MatchingParen;
1172 if (!Tok)
1173 return false;
1174 Tok = Tok->getPreviousNonComment();
1175 if (!Tok)
1176 return false;
1177 if (Tok->is(TT_DoWhile)) {
1178 const auto *Prev = Tok->getPreviousNonComment();
1179 if (!Prev) {
1180 // A do-while-loop without braces.
1181 return true;
1182 }
1183 Tok = Prev;
1184 }
1185 }
1186
1187 if (Tok->isNot(tok::r_brace))
1188 return false;
1189
1190 while (Tok->Previous && Tok->Previous->is(tok::r_brace))
1191 Tok = Tok->Previous;
1192 return Tok->NewlinesBefore > 0;
1193 };
1194
1195 if (I > 0 && C.NewlinesBefore == 0 &&
1196 DontAlignThisComment(Changes[I - 1].Tok)) {
1197 alignTrailingComments(StartOfSequence, I, MinColumn);
1198 // Reset to initial values, but skip this change for the next alignment
1199 // pass.
1200 MinColumn = 0;
1201 MaxColumn = INT_MAX;
1202 StartOfSequence = I + 1;
1203 } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
1204 (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
1205 // Break the comment sequence if the previous line did not end
1206 // in a trailing comment.
1207 (C.NewlinesBefore == 1 && I > 0 &&
1208 !Changes[I - 1].IsTrailingComment) ||
1209 WasAlignedWithStartOfNextLine) {
1210 alignTrailingComments(StartOfSequence, I, MinColumn);
1211 MinColumn = ChangeMinColumn;
1212 MaxColumn = ChangeMaxColumn;
1213 StartOfSequence = I;
1214 } else {
1215 MinColumn = std::max(MinColumn, ChangeMinColumn);
1216 MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
1217 }
1218 BreakBeforeNext = (I == 0) || (C.NewlinesBefore > 1) ||
1219 // Never start a sequence with a comment at the beginning
1220 // of the line.
1221 (C.NewlinesBefore == 1 && StartOfSequence == I);
1222 Newlines = 0;
1223 }
1224 alignTrailingComments(StartOfSequence, Size, MinColumn);
1225}
1226
1227void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
1228 unsigned Column) {
1229 for (unsigned i = Start; i != End; ++i) {
1230 int Shift = 0;
1231 if (Changes[i].IsTrailingComment)
1232 Shift = Column - Changes[i].StartOfTokenColumn;
1233 if (Changes[i].StartOfBlockComment) {
1234 Shift = Changes[i].IndentationOffset +
1235 Changes[i].StartOfBlockComment->StartOfTokenColumn -
1236 Changes[i].StartOfTokenColumn;
1237 }
1238 if (Shift <= 0)
1239 continue;
1240 Changes[i].Spaces += Shift;
1241 if (i + 1 != Changes.size())
1242 Changes[i + 1].PreviousEndOfTokenColumn += Shift;
1243 Changes[i].StartOfTokenColumn += Shift;
1244 }
1245}
1246
1247void WhitespaceManager::alignEscapedNewlines() {
1248 if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
1249 return;
1250
1251 bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
1252 unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1253 unsigned StartOfMacro = 0;
1254 for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
1255 Change &C = Changes[i];
1256 if (C.NewlinesBefore > 0) {
1257 if (C.ContinuesPPDirective) {
1258 MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
1259 } else {
1260 alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
1261 MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
1262 StartOfMacro = i;
1263 }
1264 }
1265 }
1266 alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
1267}
1268
1269void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
1270 unsigned Column) {
1271 for (unsigned i = Start; i < End; ++i) {
1272 Change &C = Changes[i];
1273 if (C.NewlinesBefore > 0) {
1274 assert(C.ContinuesPPDirective);
1275 if (C.PreviousEndOfTokenColumn + 1 > Column)
1276 C.EscapedNewlineColumn = 0;
1277 else
1278 C.EscapedNewlineColumn = Column;
1279 }
1280 }
1281}
1282
1283void WhitespaceManager::alignArrayInitializers() {
1284 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_None)
1285 return;
1286
1287 for (unsigned ChangeIndex = 1U, ChangeEnd = Changes.size();
1288 ChangeIndex < ChangeEnd; ++ChangeIndex) {
1289 auto &C = Changes[ChangeIndex];
1290 if (C.Tok->IsArrayInitializer) {
1291 bool FoundComplete = false;
1292 for (unsigned InsideIndex = ChangeIndex + 1; InsideIndex < ChangeEnd;
1293 ++InsideIndex) {
1294 if (Changes[InsideIndex].Tok == C.Tok->MatchingParen) {
1295 alignArrayInitializers(ChangeIndex, InsideIndex + 1);
1296 ChangeIndex = InsideIndex + 1;
1297 FoundComplete = true;
1298 break;
1299 }
1300 }
1301 if (!FoundComplete)
1302 ChangeIndex = ChangeEnd;
1303 }
1304 }
1305}
1306
1307void WhitespaceManager::alignArrayInitializers(unsigned Start, unsigned End) {
1308
1309 if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Right)
1310 alignArrayInitializersRightJustified(getCells(Start, End));
1311 else if (Style.AlignArrayOfStructures == FormatStyle::AIAS_Left)
1312 alignArrayInitializersLeftJustified(getCells(Start, End));
1313}
1314
1315void WhitespaceManager::alignArrayInitializersRightJustified(
1316 CellDescriptions &&CellDescs) {
1317 if (!CellDescs.isRectangular())
1318 return;
1319
1320 const int BracePadding = Style.Cpp11BracedListStyle ? 0 : 1;
1321 auto &Cells = CellDescs.Cells;
1322 // Now go through and fixup the spaces.
1323 auto *CellIter = Cells.begin();
1324 for (auto i = 0U; i < CellDescs.CellCounts[0]; ++i, ++CellIter) {
1325 unsigned NetWidth = 0U;
1326 if (isSplitCell(*CellIter))
1327 NetWidth = getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1328 auto CellWidth = getMaximumCellWidth(CellIter, NetWidth);
1329
1330 if (Changes[CellIter->Index].Tok->is(tok::r_brace)) {
1331 // So in here we want to see if there is a brace that falls
1332 // on a line that was split. If so on that line we make sure that
1333 // the spaces in front of the brace are enough.
1334 const auto *Next = CellIter;
1335 do {
1336 const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
1337 if (Previous && Previous->isNot(TT_LineComment)) {
1338 Changes[Next->Index].Spaces = BracePadding;
1339 Changes[Next->Index].NewlinesBefore = 0;
1340 }
1341 Next = Next->NextColumnElement;
1342 } while (Next);
1343 // Unless the array is empty, we need the position of all the
1344 // immediately adjacent cells
1345 if (CellIter != Cells.begin()) {
1346 auto ThisNetWidth =
1347 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1348 auto MaxNetWidth = getMaximumNetWidth(
1349 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1350 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1351 if (ThisNetWidth < MaxNetWidth)
1352 Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1353 auto RowCount = 1U;
1354 auto Offset = std::distance(Cells.begin(), CellIter);
1355 for (const auto *Next = CellIter->NextColumnElement; Next;
1356 Next = Next->NextColumnElement) {
1357 if (RowCount >= CellDescs.CellCounts.size())
1358 break;
1359 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1360 auto *End = Start + Offset;
1361 ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1362 if (ThisNetWidth < MaxNetWidth)
1363 Changes[Next->Index].Spaces = (MaxNetWidth - ThisNetWidth);
1364 ++RowCount;
1365 }
1366 }
1367 } else {
1368 auto ThisWidth =
1369 calculateCellWidth(CellIter->Index, CellIter->EndIndex, true) +
1370 NetWidth;
1371 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1372 Changes[CellIter->Index].Spaces = (CellWidth - (ThisWidth + NetWidth));
1373 Changes[CellIter->Index].Spaces += (i > 0) ? 1 : BracePadding;
1374 }
1375 alignToStartOfCell(CellIter->Index, CellIter->EndIndex);
1376 for (const auto *Next = CellIter->NextColumnElement; Next;
1377 Next = Next->NextColumnElement) {
1378 ThisWidth =
1379 calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth;
1380 if (Changes[Next->Index].NewlinesBefore == 0) {
1381 Changes[Next->Index].Spaces = (CellWidth - ThisWidth);
1382 Changes[Next->Index].Spaces += (i > 0) ? 1 : BracePadding;
1383 }
1384 alignToStartOfCell(Next->Index, Next->EndIndex);
1385 }
1386 }
1387 }
1388}
1389
1390void WhitespaceManager::alignArrayInitializersLeftJustified(
1391 CellDescriptions &&CellDescs) {
1392
1393 if (!CellDescs.isRectangular())
1394 return;
1395
1396 const int BracePadding = Style.Cpp11BracedListStyle ? 0 : 1;
1397 auto &Cells = CellDescs.Cells;
1398 // Now go through and fixup the spaces.
1399 auto *CellIter = Cells.begin();
1400 // The first cell of every row needs to be against the left brace.
1401 for (const auto *Next = CellIter; Next; Next = Next->NextColumnElement) {
1402 auto &Change = Changes[Next->Index];
1403 Change.Spaces =
1404 Change.NewlinesBefore == 0 ? BracePadding : CellDescs.InitialSpaces;
1405 }
1406 ++CellIter;
1407 for (auto i = 1U; i < CellDescs.CellCounts[0]; i++, ++CellIter) {
1408 auto MaxNetWidth = getMaximumNetWidth(
1409 Cells.begin(), CellIter, CellDescs.InitialSpaces,
1410 CellDescs.CellCounts[0], CellDescs.CellCounts.size());
1411 auto ThisNetWidth =
1412 getNetWidth(Cells.begin(), CellIter, CellDescs.InitialSpaces);
1413 if (Changes[CellIter->Index].NewlinesBefore == 0) {
1414 Changes[CellIter->Index].Spaces =
1415 MaxNetWidth - ThisNetWidth +
1416 (Changes[CellIter->Index].Tok->isNot(tok::r_brace) ? 1
1417 : BracePadding);
1418 }
1419 auto RowCount = 1U;
1420 auto Offset = std::distance(Cells.begin(), CellIter);
1421 for (const auto *Next = CellIter->NextColumnElement; Next;
1422 Next = Next->NextColumnElement) {
1423 if (RowCount >= CellDescs.CellCounts.size())
1424 break;
1425 auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
1426 auto *End = Start + Offset;
1427 auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);
1428 if (Changes[Next->Index].NewlinesBefore == 0) {
1429 Changes[Next->Index].Spaces =
1430 MaxNetWidth - ThisNetWidth +
1431 (Changes[Next->Index].Tok->isNot(tok::r_brace) ? 1 : BracePadding);
1432 }
1433 ++RowCount;
1434 }
1435 }
1436}
1437
1438bool WhitespaceManager::isSplitCell(const CellDescription &Cell) {
1439 if (Cell.HasSplit)
1440 return true;
1441 for (const auto *Next = Cell.NextColumnElement; Next;
1442 Next = Next->NextColumnElement) {
1443 if (Next->HasSplit)
1444 return true;
1445 }
1446 return false;
1447}
1448
1449WhitespaceManager::CellDescriptions WhitespaceManager::getCells(unsigned Start,
1450 unsigned End) {
1451
1452 unsigned Depth = 0;
1453 unsigned Cell = 0;
1454 SmallVector<unsigned> CellCounts;
1455 unsigned InitialSpaces = 0;
1456 unsigned InitialTokenLength = 0;
1457 unsigned EndSpaces = 0;
1458 SmallVector<CellDescription> Cells;
1459 const FormatToken *MatchingParen = nullptr;
1460 for (unsigned i = Start; i < End; ++i) {
1461 auto &C = Changes[i];
1462 if (C.Tok->is(tok::l_brace))
1463 ++Depth;
1464 else if (C.Tok->is(tok::r_brace))
1465 --Depth;
1466 if (Depth == 2) {
1467 if (C.Tok->is(tok::l_brace)) {
1468 Cell = 0;
1469 MatchingParen = C.Tok->MatchingParen;
1470 if (InitialSpaces == 0) {
1471 InitialSpaces = C.Spaces + C.TokenLength;
1472 InitialTokenLength = C.TokenLength;
1473 auto j = i - 1;
1474 for (; Changes[j].NewlinesBefore == 0 && j > Start; --j) {
1475 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1476 InitialTokenLength += Changes[j].TokenLength;
1477 }
1478 if (C.NewlinesBefore == 0) {
1479 InitialSpaces += Changes[j].Spaces + Changes[j].TokenLength;
1480 InitialTokenLength += Changes[j].TokenLength;
1481 }
1482 }
1483 } else if (C.Tok->is(tok::comma)) {
1484 if (!Cells.empty())
1485 Cells.back().EndIndex = i;
1486 if (const auto *Next = C.Tok->getNextNonComment();
1487 Next && Next->isNot(tok::r_brace)) { // dangling comma
1488 ++Cell;
1489 }
1490 }
1491 } else if (Depth == 1) {
1492 if (C.Tok == MatchingParen) {
1493 if (!Cells.empty())
1494 Cells.back().EndIndex = i;
1495 Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr});
1496 CellCounts.push_back(C.Tok->Previous->isNot(tok::comma) ? Cell + 1
1497 : Cell);
1498 // Go to the next non-comment and ensure there is a break in front
1499 const auto *NextNonComment = C.Tok->getNextNonComment();
1500 while (NextNonComment && NextNonComment->is(tok::comma))
1501 NextNonComment = NextNonComment->getNextNonComment();
1502 auto j = i;
1503 while (j < End && Changes[j].Tok != NextNonComment)
1504 ++j;
1505 if (j < End && Changes[j].NewlinesBefore == 0 &&
1506 Changes[j].Tok->isNot(tok::r_brace)) {
1507 Changes[j].NewlinesBefore = 1;
1508 // Account for the added token lengths
1509 Changes[j].Spaces = InitialSpaces - InitialTokenLength;
1510 }
1511 } else if (C.Tok->is(tok::comment) && C.Tok->NewlinesBefore == 0) {
1512 // Trailing comments stay at a space past the last token
1513 C.Spaces = Changes[i - 1].Tok->is(tok::comma) ? 1 : 2;
1514 } else if (C.Tok->is(tok::l_brace)) {
1515 // We need to make sure that the ending braces is aligned to the
1516 // start of our initializer
1517 auto j = i - 1;
1518 for (; j > 0 && !Changes[j].Tok->ArrayInitializerLineStart; --j)
1519 ; // Nothing the loop does the work
1520 EndSpaces = Changes[j].Spaces;
1521 }
1522 } else if (Depth == 0 && C.Tok->is(tok::r_brace)) {
1523 C.NewlinesBefore = 1;
1524 C.Spaces = EndSpaces;
1525 }
1526 if (C.Tok->StartsColumn) {
1527 // This gets us past tokens that have been split over multiple
1528 // lines
1529 bool HasSplit = false;
1530 if (Changes[i].NewlinesBefore > 0) {
1531 // So if we split a line previously and the tail line + this token is
1532 // less then the column limit we remove the split here and just put
1533 // the column start at a space past the comma
1534 //
1535 // FIXME This if branch covers the cases where the column is not
1536 // the first column. This leads to weird pathologies like the formatting
1537 // auto foo = Items{
1538 // Section{
1539 // 0, bar(),
1540 // }
1541 // };
1542 // Well if it doesn't lead to that it's indicative that the line
1543 // breaking should be revisited. Unfortunately alot of other options
1544 // interact with this
1545 auto j = i - 1;
1546 if ((j - 1) > Start && Changes[j].Tok->is(tok::comma) &&
1547 Changes[j - 1].NewlinesBefore > 0) {
1548 --j;
1549 auto LineLimit = Changes[j].Spaces + Changes[j].TokenLength;
1550 if (LineLimit < Style.ColumnLimit) {
1551 Changes[i].NewlinesBefore = 0;
1552 Changes[i].Spaces = 1;
1553 }
1554 }
1555 }
1556 while (Changes[i].NewlinesBefore > 0 && Changes[i].Tok == C.Tok) {
1557 Changes[i].Spaces = InitialSpaces;
1558 ++i;
1559 HasSplit = true;
1560 }
1561 if (Changes[i].Tok != C.Tok)
1562 --i;
1563 Cells.push_back(CellDescription{i, Cell, i, HasSplit, nullptr});
1564 }
1565 }
1566
1567 return linkCells({Cells, CellCounts, InitialSpaces});
1568}
1569
1570unsigned WhitespaceManager::calculateCellWidth(unsigned Start, unsigned End,
1571 bool WithSpaces) const {
1572 unsigned CellWidth = 0;
1573 for (auto i = Start; i < End; i++) {
1574 if (Changes[i].NewlinesBefore > 0)
1575 CellWidth = 0;
1576 CellWidth += Changes[i].TokenLength;
1577 CellWidth += (WithSpaces ? Changes[i].Spaces : 0);
1578 }
1579 return CellWidth;
1580}
1581
1582void WhitespaceManager::alignToStartOfCell(unsigned Start, unsigned End) {
1583 if ((End - Start) <= 1)
1584 return;
1585 // If the line is broken anywhere in there make sure everything
1586 // is aligned to the parent
1587 for (auto i = Start + 1; i < End; i++)
1588 if (Changes[i].NewlinesBefore > 0)
1589 Changes[i].Spaces = Changes[Start].Spaces;
1590}
1591
1592WhitespaceManager::CellDescriptions
1593WhitespaceManager::linkCells(CellDescriptions &&CellDesc) {
1594 auto &Cells = CellDesc.Cells;
1595 for (auto *CellIter = Cells.begin(); CellIter != Cells.end(); ++CellIter) {
1596 if (!CellIter->NextColumnElement && (CellIter + 1) != Cells.end()) {
1597 for (auto *NextIter = CellIter + 1; NextIter != Cells.end(); ++NextIter) {
1598 if (NextIter->Cell == CellIter->Cell) {
1599 CellIter->NextColumnElement = &(*NextIter);
1600 break;
1601 }
1602 }
1603 }
1604 }
1605 return std::move(CellDesc);
1606}
1607
1608void WhitespaceManager::generateChanges() {
1609 for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
1610 const Change &C = Changes[i];
1611 if (i > 0) {
1612 auto Last = Changes[i - 1].OriginalWhitespaceRange;
1613 auto New = Changes[i].OriginalWhitespaceRange;
1614 // Do not generate two replacements for the same location. As a special
1615 // case, it is allowed if there is a replacement for the empty range
1616 // between 2 tokens and another non-empty range at the start of the second
1617 // token. We didn't implement logic to combine replacements for 2
1618 // consecutive source ranges into a single replacement, because the
1619 // program works fine without it.
1620 //
1621 // We can't eliminate empty original whitespace ranges. They appear when
1622 // 2 tokens have no whitespace in between in the input. It does not
1623 // matter whether whitespace is to be added. If no whitespace is to be
1624 // added, the replacement will be empty, and it gets eliminated after this
1625 // step in storeReplacement. For example, if the input is `foo();`,
1626 // there will be a replacement for the range between every consecutive
1627 // pair of tokens.
1628 //
1629 // A replacement at the start of a token can be added by
1630 // BreakableStringLiteralUsingOperators::insertBreak when it adds braces
1631 // around the string literal. Say Verilog code is being formatted and the
1632 // first line is to become the next 2 lines.
1633 // x("long string");
1634 // x({"long ",
1635 // "string"});
1636 // There will be a replacement for the empty range between the parenthesis
1637 // and the string and another replacement for the quote character. The
1638 // replacement for the empty range between the parenthesis and the quote
1639 // comes from ContinuationIndenter::addTokenOnCurrentLine when it changes
1640 // the original empty range between the parenthesis and the string to
1641 // another empty one. The replacement for the quote character comes from
1642 // BreakableStringLiteralUsingOperators::insertBreak when it adds the
1643 // brace. In the example, the replacement for the empty range is the same
1644 // as the original text. However, eliminating replacements that are same
1645 // as the original does not help in general. For example, a newline can
1646 // be inserted, causing the first line to become the next 3 lines.
1647 // xxxxxxxxxxx("long string");
1648 // xxxxxxxxxxx(
1649 // {"long ",
1650 // "string"});
1651 // In that case, the empty range between the parenthesis and the string
1652 // will be replaced by a newline and 4 spaces. So we will still have to
1653 // deal with a replacement for an empty source range followed by a
1654 // replacement for a non-empty source range.
1655 if (Last.getBegin() == New.getBegin() &&
1656 (Last.getEnd() != Last.getBegin() ||
1657 New.getEnd() == New.getBegin())) {
1658 continue;
1659 }
1660 }
1661 if (C.CreateReplacement) {
1662 std::string ReplacementText = C.PreviousLinePostfix;
1663 if (C.ContinuesPPDirective) {
1664 appendEscapedNewlineText(ReplacementText, C.NewlinesBefore,
1665 C.PreviousEndOfTokenColumn,
1666 C.EscapedNewlineColumn);
1667 } else {
1668 appendNewlineText(ReplacementText, C.NewlinesBefore);
1669 }
1670 // FIXME: This assert should hold if we computed the column correctly.
1671 // assert((int)C.StartOfTokenColumn >= C.Spaces);
1672 appendIndentText(
1673 ReplacementText, C.Tok->IndentLevel, std::max(0, C.Spaces),
1674 std::max((int)C.StartOfTokenColumn, C.Spaces) - std::max(0, C.Spaces),
1675 C.IsAligned);
1676 ReplacementText.append(C.CurrentLinePrefix);
1677 storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
1678 }
1679 }
1680}
1681
1682void WhitespaceManager::storeReplacement(SourceRange Range, StringRef Text) {
1683 unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
1684 SourceMgr.getFileOffset(Range.getBegin());
1685 // Don't create a replacement, if it does not change anything.
1686 if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
1687 WhitespaceLength) == Text) {
1688 return;
1689 }
1690 auto Err = Replaces.add(tooling::Replacement(
1692 // FIXME: better error handling. For now, just print an error message in the
1693 // release version.
1694 if (Err) {
1695 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
1696 assert(false);
1697 }
1698}
1699
1700void WhitespaceManager::appendNewlineText(std::string &Text,
1701 unsigned Newlines) {
1702 if (UseCRLF) {
1703 Text.reserve(Text.size() + 2 * Newlines);
1704 for (unsigned i = 0; i < Newlines; ++i)
1705 Text.append("\r\n");
1706 } else {
1707 Text.append(Newlines, '\n');
1708 }
1709}
1710
1711void WhitespaceManager::appendEscapedNewlineText(
1712 std::string &Text, unsigned Newlines, unsigned PreviousEndOfTokenColumn,
1713 unsigned EscapedNewlineColumn) {
1714 if (Newlines > 0) {
1715 unsigned Spaces =
1716 std::max<int>(1, EscapedNewlineColumn - PreviousEndOfTokenColumn - 1);
1717 for (unsigned i = 0; i < Newlines; ++i) {
1718 Text.append(Spaces, ' ');
1719 Text.append(UseCRLF ? "\\\r\n" : "\\\n");
1720 Spaces = std::max<int>(0, EscapedNewlineColumn - 1);
1721 }
1722 }
1723}
1724
1725void WhitespaceManager::appendIndentText(std::string &Text,
1726 unsigned IndentLevel, unsigned Spaces,
1727 unsigned WhitespaceStartColumn,
1728 bool IsAligned) {
1729 switch (Style.UseTab) {
1731 Text.append(Spaces, ' ');
1732 break;
1734 if (Style.TabWidth) {
1735 unsigned FirstTabWidth =
1736 Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
1737
1738 // Insert only spaces when we want to end up before the next tab.
1739 if (Spaces < FirstTabWidth || Spaces == 1) {
1740 Text.append(Spaces, ' ');
1741 break;
1742 }
1743 // Align to the next tab.
1744 Spaces -= FirstTabWidth;
1745 Text.append("\t");
1746
1747 Text.append(Spaces / Style.TabWidth, '\t');
1748 Text.append(Spaces % Style.TabWidth, ' ');
1749 } else if (Spaces == 1) {
1750 Text.append(Spaces, ' ');
1751 }
1752 break;
1753 }
1755 if (WhitespaceStartColumn == 0) {
1756 unsigned Indentation = IndentLevel * Style.IndentWidth;
1757 Spaces = appendTabIndent(Text, Spaces, Indentation);
1758 }
1759 Text.append(Spaces, ' ');
1760 break;
1762 if (WhitespaceStartColumn == 0)
1763 Spaces = appendTabIndent(Text, Spaces, Spaces);
1764 Text.append(Spaces, ' ');
1765 break;
1767 if (WhitespaceStartColumn == 0) {
1768 unsigned Indentation =
1769 IsAligned ? IndentLevel * Style.IndentWidth : Spaces;
1770 Spaces = appendTabIndent(Text, Spaces, Indentation);
1771 }
1772 Text.append(Spaces, ' ');
1773 break;
1774 }
1775}
1776
1777unsigned WhitespaceManager::appendTabIndent(std::string &Text, unsigned Spaces,
1778 unsigned Indentation) {
1779 // This happens, e.g. when a line in a block comment is indented less than the
1780 // first one.
1781 if (Indentation > Spaces)
1782 Indentation = Spaces;
1783 if (Style.TabWidth) {
1784 unsigned Tabs = Indentation / Style.TabWidth;
1785 Text.append(Tabs, '\t');
1786 Spaces -= Tabs * Style.TabWidth;
1787 }
1788 return Spaces;
1789}
1790
1791} // namespace format
1792} // namespace clang
MatchType Type
StringRef P
StringRef Text
Definition: Format.cpp:2976
SourceRange Range
Definition: SemaObjC.cpp:754
StateNode * Previous
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.
unsigned getFileOffset(SourceLocation SpellingLoc) const
Returns the offset from the start of the file that the specified SourceLocation represents.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
unsigned getSpellingColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
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.
Definition: Replacement.h:212
llvm::Error add(const Replacement &R)
Adds a new replacement R to the current set of replacements.
#define INT_MAX
Definition: limits.h:50
@ MR_ExpandedArg
The token was expanded from a macro argument when formatting the expanded token sequence.
Definition: FormatToken.h:227
static void AlignMatchingTokenSequence(unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn, std::function< bool(const WhitespaceManager::Change &C)> Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes)
static unsigned AlignTokens(const FormatStyle &Style, F &&Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes, unsigned StartAt, const FormatStyle::AlignConsecutiveStyle &ACS={}, bool RightJustify=false)
static void AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End, unsigned Column, bool RightJustify, F &&Matches, SmallVector< WhitespaceManager::Change, 16 > &Changes)
TokenType
Determines the semantic type of a syntactic token, e.g.
Definition: FormatToken.h:205
The JSON file list parser is used to communicate input to InstallAPI.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
for(const auto &A :T->param_types())
#define false
Definition: stdbool.h:26
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:55
@ UT_AlignWithSpaces
Use tabs for line continuation and indentation, and spaces for alignment.
Definition: Format.h:4892
@ UT_ForContinuationAndIndentation
Fill all leading whitespace with tabs, and use spaces for alignment that appears within a line (e....
Definition: Format.h:4889
@ UT_ForIndentation
Use tabs only for indentation.
Definition: Format.h:4886
@ UT_Always
Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one.
Definition: Format.h:4895
@ UT_Never
Never use tab.
Definition: Format.h:4884
bool isTableGen() const
Definition: Format.h:3182
@ TCAS_Never
Don't align trailing comments but other formatter applies.
Definition: Format.h:573
@ TCAS_Leave
Leave trailing comments as they are.
Definition: Format.h:555
@ TCAS_Always
Align trailing comments.
Definition: Format.h:564
@ AIAS_Left
Align array column and left justify the columns e.g.:
Definition: Format.h:120
@ AIAS_Right
Align array column and right justify the columns e.g.:
Definition: Format.h:130
@ AIAS_None
Don't align array initializer columns.
Definition: Format.h:132
@ ENAS_DontAlign
Don't align escaped newlines.
Definition: Format.h:480
@ ENAS_Left
Align escaped newlines as far left as possible.
Definition: Format.h:491
@ PAS_Right
Align pointer to the right.
Definition: Format.h:3561
@ RAS_Right
Align reference to the right.
Definition: Format.h:3733
@ RAS_Pointer
Align reference like PointerAlignment.
Definition: Format.h:3723
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:290
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
Definition: FormatToken.h:500
SourceLocation getStartOfNonWhitespace() const
Returns actual token start location without leading escaped newlines and whitespace.
Definition: FormatToken.h:785
void setDecision(FormatDecision D)
Definition: FormatToken.h:398
unsigned Finalized
If true, this token has been fully formatted (indented and potentially re-formatted inside),...
Definition: FormatToken.h:369
std::optional< MacroExpansion > MacroCtx
Definition: FormatToken.h:591
unsigned NewlinesBefore
The number of newlines immediately before the Token.
Definition: FormatToken.h:459
unsigned IsFirst
Indicates that this is the first token of the file.
Definition: FormatToken.h:329
SourceRange WhitespaceRange
The range of the whitespace immediately preceding the Token.
Definition: FormatToken.h:319
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.