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