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