1 //===--- WhitespaceManager.cpp - Format C++ code --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements WhitespaceManager class.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "WhitespaceManager.h"
16 #include "llvm/ADT/STLExtras.h"
17 
18 namespace clang {
19 namespace format {
20 
21 bool WhitespaceManager::Change::IsBeforeInFile::
22 operator()(const Change &C1, const Change &C2) const {
23   return SourceMgr.isBeforeInTranslationUnit(
24       C1.OriginalWhitespaceRange.getBegin(),
25       C2.OriginalWhitespaceRange.getBegin());
26 }
27 
28 WhitespaceManager::Change::Change(
29     bool CreateReplacement, SourceRange OriginalWhitespaceRange,
30     unsigned IndentLevel, int Spaces, unsigned StartOfTokenColumn,
31     unsigned NewlinesBefore, StringRef PreviousLinePostfix,
32     StringRef CurrentLinePrefix, tok::TokenKind Kind, bool ContinuesPPDirective,
33     bool IsStartOfDeclName)
34     : CreateReplacement(CreateReplacement),
35       OriginalWhitespaceRange(OriginalWhitespaceRange),
36       StartOfTokenColumn(StartOfTokenColumn), NewlinesBefore(NewlinesBefore),
37       PreviousLinePostfix(PreviousLinePostfix),
38       CurrentLinePrefix(CurrentLinePrefix), Kind(Kind),
39       ContinuesPPDirective(ContinuesPPDirective),
40       IsStartOfDeclName(IsStartOfDeclName), IndentLevel(IndentLevel),
41       Spaces(Spaces), IsTrailingComment(false), TokenLength(0),
42       PreviousEndOfTokenColumn(0), EscapedNewlineColumn(0),
43       StartOfBlockComment(nullptr), IndentationOffset(0) {}
44 
45 void WhitespaceManager::reset() {
46   Changes.clear();
47   Replaces.clear();
48 }
49 
50 void WhitespaceManager::replaceWhitespace(FormatToken &Tok, unsigned Newlines,
51                                           unsigned IndentLevel, unsigned Spaces,
52                                           unsigned StartOfTokenColumn,
53                                           bool InPPDirective) {
54   if (Tok.Finalized)
55     return;
56   Tok.Decision = (Newlines > 0) ? FD_Break : FD_Continue;
57   Changes.push_back(
58       Change(true, Tok.WhitespaceRange, IndentLevel, Spaces, StartOfTokenColumn,
59              Newlines, "", "", Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst,
60              Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
61 }
62 
63 void WhitespaceManager::addUntouchableToken(const FormatToken &Tok,
64                                             bool InPPDirective) {
65   if (Tok.Finalized)
66     return;
67   Changes.push_back(
68       Change(false, Tok.WhitespaceRange, /*IndentLevel=*/0,
69              /*Spaces=*/0, Tok.OriginalColumn, Tok.NewlinesBefore, "", "",
70              Tok.Tok.getKind(), InPPDirective && !Tok.IsFirst,
71              Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
72 }
73 
74 void WhitespaceManager::replaceWhitespaceInToken(
75     const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars,
76     StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective,
77     unsigned Newlines, unsigned IndentLevel, int Spaces) {
78   if (Tok.Finalized)
79     return;
80   SourceLocation Start = Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
81   Changes.push_back(Change(
82       true, SourceRange(Start, Start.getLocWithOffset(ReplaceChars)),
83       IndentLevel, Spaces, std::max(0, Spaces), Newlines, PreviousPostfix,
84       CurrentPrefix,
85       // If we don't add a newline this change doesn't start a comment. Thus,
86       // when we align line comments, we don't need to treat this change as one.
87       // FIXME: We still need to take this change in account to properly
88       // calculate the new length of the comment and to calculate the changes
89       // for which to do the alignment when aligning comments.
90       Tok.is(TT_LineComment) && Newlines > 0 ? tok::comment : tok::unknown,
91       InPPDirective && !Tok.IsFirst,
92       Tok.is(TT_StartOfName) || Tok.is(TT_FunctionDeclarationName)));
93 }
94 
95 const tooling::Replacements &WhitespaceManager::generateReplacements() {
96   if (Changes.empty())
97     return Replaces;
98 
99   std::sort(Changes.begin(), Changes.end(), Change::IsBeforeInFile(SourceMgr));
100   calculateLineBreakInformation();
101   alignConsecutiveDeclarations();
102   alignConsecutiveAssignments();
103   alignTrailingComments();
104   alignEscapedNewlines();
105   generateChanges();
106 
107   return Replaces;
108 }
109 
110 void WhitespaceManager::calculateLineBreakInformation() {
111   Changes[0].PreviousEndOfTokenColumn = 0;
112   for (unsigned i = 1, e = Changes.size(); i != e; ++i) {
113     unsigned OriginalWhitespaceStart =
114         SourceMgr.getFileOffset(Changes[i].OriginalWhitespaceRange.getBegin());
115     unsigned PreviousOriginalWhitespaceEnd = SourceMgr.getFileOffset(
116         Changes[i - 1].OriginalWhitespaceRange.getEnd());
117     Changes[i - 1].TokenLength = OriginalWhitespaceStart -
118                                  PreviousOriginalWhitespaceEnd +
119                                  Changes[i].PreviousLinePostfix.size() +
120                                  Changes[i - 1].CurrentLinePrefix.size();
121 
122     Changes[i].PreviousEndOfTokenColumn =
123         Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength;
124 
125     Changes[i - 1].IsTrailingComment =
126         (Changes[i].NewlinesBefore > 0 || Changes[i].Kind == tok::eof) &&
127         Changes[i - 1].Kind == tok::comment;
128   }
129   // FIXME: The last token is currently not always an eof token; in those
130   // cases, setting TokenLength of the last token to 0 is wrong.
131   Changes.back().TokenLength = 0;
132   Changes.back().IsTrailingComment = Changes.back().Kind == tok::comment;
133 
134   const WhitespaceManager::Change *LastBlockComment = nullptr;
135   for (auto &Change : Changes) {
136     Change.StartOfBlockComment = nullptr;
137     Change.IndentationOffset = 0;
138     if (Change.Kind == tok::comment) {
139       LastBlockComment = &Change;
140     } else if (Change.Kind == tok::unknown) {
141       if ((Change.StartOfBlockComment = LastBlockComment))
142         Change.IndentationOffset =
143             Change.StartOfTokenColumn -
144             Change.StartOfBlockComment->StartOfTokenColumn;
145     } else {
146       LastBlockComment = nullptr;
147     }
148   }
149 }
150 
151 // Walk through all of the changes and find sequences of "=" to align.  To do
152 // so, keep track of the lines and whether or not an "=" was found on align. If
153 // a "=" is found on a line, extend the current sequence. If the current line
154 // cannot be part of a sequence, e.g. because there is an empty line before it
155 // or it contains non-assignments, finalize the previous sequence.
156 void WhitespaceManager::alignConsecutiveAssignments() {
157   if (!Style.AlignConsecutiveAssignments)
158     return;
159 
160   unsigned MinColumn = 0;
161   unsigned MaxColumn = UINT_MAX;
162   unsigned StartOfSequence = 0;
163   unsigned EndOfSequence = 0;
164   bool FoundAssignmentOnLine = false;
165   bool FoundLeftParenOnLine = false;
166 
167   // Aligns a sequence of assignment tokens, on the MinColumn column.
168   //
169   // Sequences start from the first assignment token to align, and end at the
170   // first token of the first line that doesn't need to be aligned.
171   //
172   // We need to adjust the StartOfTokenColumn of each Change that is on a line
173   // containing any assignment to be aligned and located after such assignment
174   auto AlignSequence = [&] {
175     if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
176       alignConsecutiveAssignments(StartOfSequence, EndOfSequence, MinColumn);
177     MinColumn = 0;
178     MaxColumn = UINT_MAX;
179     StartOfSequence = 0;
180     EndOfSequence = 0;
181   };
182 
183   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
184     if (Changes[i].NewlinesBefore > 0) {
185       EndOfSequence = i;
186       // If there is a blank line or if the last line didn't contain any
187       // assignment, the sequence ends here.
188       if (Changes[i].NewlinesBefore > 1 || !FoundAssignmentOnLine) {
189         // NB: In the latter case, the sequence should end at the beggining of
190         // the previous line, but it doesn't really matter as there is no
191         // assignment on it
192         AlignSequence();
193       }
194 
195       FoundAssignmentOnLine = false;
196       FoundLeftParenOnLine = false;
197     }
198 
199     // If there is more than one "=" per line, or if the "=" appears first on
200     // the line of if it appears last, end the sequence
201     if (Changes[i].Kind == tok::equal &&
202         (FoundAssignmentOnLine || Changes[i].NewlinesBefore > 0 ||
203          Changes[i + 1].NewlinesBefore > 0)) {
204       AlignSequence();
205     } else if (!FoundLeftParenOnLine && Changes[i].Kind == tok::r_paren) {
206       AlignSequence();
207     } else if (Changes[i].Kind == tok::l_paren) {
208       FoundLeftParenOnLine = true;
209       if (!FoundAssignmentOnLine)
210         AlignSequence();
211     } else if (!FoundAssignmentOnLine && !FoundLeftParenOnLine &&
212                Changes[i].Kind == tok::equal) {
213       FoundAssignmentOnLine = true;
214       if (StartOfSequence == 0)
215         StartOfSequence = i;
216 
217       unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
218       int LineLengthAfter = -Changes[i].Spaces;
219       for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
220         LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
221       unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
222 
223       if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) {
224         AlignSequence();
225         StartOfSequence = i;
226       }
227 
228       MinColumn = std::max(MinColumn, ChangeMinColumn);
229       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
230     }
231   }
232 
233   EndOfSequence = Changes.size();
234   AlignSequence();
235 }
236 
237 void WhitespaceManager::alignConsecutiveAssignments(unsigned Start,
238                                                     unsigned End,
239                                                     unsigned Column) {
240   bool FoundAssignmentOnLine = false;
241   int Shift = 0;
242   for (unsigned i = Start; i != End; ++i) {
243     if (Changes[i].NewlinesBefore > 0) {
244       FoundAssignmentOnLine = false;
245       Shift = 0;
246     }
247 
248     // If this is the first assignment to be aligned, remember by how many
249     // spaces it has to be shifted, so the rest of the changes on the line are
250     // shifted by the same amount
251     if (!FoundAssignmentOnLine && Changes[i].Kind == tok::equal) {
252       FoundAssignmentOnLine = true;
253       Shift = Column - Changes[i].StartOfTokenColumn;
254       Changes[i].Spaces += Shift;
255     }
256 
257     assert(Shift >= 0);
258     Changes[i].StartOfTokenColumn += Shift;
259     if (i + 1 != Changes.size())
260       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
261   }
262 }
263 
264 // Walk through all of the changes and find sequences of declaration names to
265 // align.  To do so, keep track of the lines and whether or not a name was found
266 // on align. If a name is found on a line, extend the current sequence. If the
267 // current line cannot be part of a sequence, e.g. because there is an empty
268 // line before it or it contains non-declarations, finalize the previous
269 // sequence.
270 void WhitespaceManager::alignConsecutiveDeclarations() {
271   if (!Style.AlignConsecutiveDeclarations)
272     return;
273 
274   unsigned MinColumn = 0;
275   unsigned MaxColumn = UINT_MAX;
276   unsigned StartOfSequence = 0;
277   unsigned EndOfSequence = 0;
278   bool FoundDeclarationOnLine = false;
279   bool FoundLeftBraceOnLine = false;
280   bool FoundLeftParenOnLine = false;
281 
282   auto AlignSequence = [&] {
283     if (StartOfSequence > 0 && StartOfSequence < EndOfSequence)
284       alignConsecutiveDeclarations(StartOfSequence, EndOfSequence, MinColumn);
285     MinColumn = 0;
286     MaxColumn = UINT_MAX;
287     StartOfSequence = 0;
288     EndOfSequence = 0;
289   };
290 
291   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
292     if (Changes[i].NewlinesBefore != 0) {
293       EndOfSequence = i;
294       if (Changes[i].NewlinesBefore > 1 || !FoundDeclarationOnLine ||
295           FoundLeftBraceOnLine || FoundLeftParenOnLine)
296         AlignSequence();
297       FoundDeclarationOnLine = false;
298       FoundLeftBraceOnLine = false;
299       FoundLeftParenOnLine = false;
300     }
301 
302     if (Changes[i].Kind == tok::r_brace) {
303       if (!FoundLeftBraceOnLine)
304         AlignSequence();
305       FoundLeftBraceOnLine = false;
306     } else if (Changes[i].Kind == tok::l_brace) {
307       FoundLeftBraceOnLine = true;
308       if (!FoundDeclarationOnLine)
309         AlignSequence();
310     } else if (Changes[i].Kind == tok::r_paren) {
311       if (!FoundLeftParenOnLine)
312         AlignSequence();
313       FoundLeftParenOnLine = false;
314     } else if (Changes[i].Kind == tok::l_paren) {
315       FoundLeftParenOnLine = true;
316       if (!FoundDeclarationOnLine)
317         AlignSequence();
318     } else if (!FoundDeclarationOnLine && !FoundLeftBraceOnLine &&
319                !FoundLeftParenOnLine && Changes[i].IsStartOfDeclName) {
320       FoundDeclarationOnLine = true;
321       if (StartOfSequence == 0)
322         StartOfSequence = i;
323 
324       unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
325       int LineLengthAfter = -Changes[i].Spaces;
326       for (unsigned j = i; j != e && Changes[j].NewlinesBefore == 0; ++j)
327         LineLengthAfter += Changes[j].Spaces + Changes[j].TokenLength;
328       unsigned ChangeMaxColumn = Style.ColumnLimit - LineLengthAfter;
329 
330       if (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) {
331         AlignSequence();
332         StartOfSequence = i;
333       }
334 
335       MinColumn = std::max(MinColumn, ChangeMinColumn);
336       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
337     }
338   }
339 
340   EndOfSequence = Changes.size();
341   AlignSequence();
342 }
343 
344 void WhitespaceManager::alignConsecutiveDeclarations(unsigned Start,
345                                                      unsigned End,
346                                                      unsigned Column) {
347   bool FoundDeclarationOnLine = false;
348   int Shift = 0;
349   for (unsigned i = Start; i != End; ++i) {
350     if (Changes[i].NewlinesBefore != 0) {
351       FoundDeclarationOnLine = false;
352       Shift = 0;
353     }
354 
355     if (!FoundDeclarationOnLine && Changes[i].IsStartOfDeclName) {
356       FoundDeclarationOnLine = true;
357       Shift = Column - Changes[i].StartOfTokenColumn;
358       Changes[i].Spaces += Shift;
359     }
360 
361     assert(Shift >= 0);
362     Changes[i].StartOfTokenColumn += Shift;
363     if (i + 1 != Changes.size())
364       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
365   }
366 }
367 
368 void WhitespaceManager::alignTrailingComments() {
369   unsigned MinColumn = 0;
370   unsigned MaxColumn = UINT_MAX;
371   unsigned StartOfSequence = 0;
372   bool BreakBeforeNext = false;
373   unsigned Newlines = 0;
374   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
375     if (Changes[i].StartOfBlockComment)
376       continue;
377     Newlines += Changes[i].NewlinesBefore;
378     if (!Changes[i].IsTrailingComment)
379       continue;
380 
381     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
382     unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
383     if (i + 1 != e && Changes[i + 1].ContinuesPPDirective)
384       ChangeMaxColumn -= 2;
385     // If this comment follows an } in column 0, it probably documents the
386     // closing of a namespace and we don't want to align it.
387     bool FollowsRBraceInColumn0 = i > 0 && Changes[i].NewlinesBefore == 0 &&
388                                   Changes[i - 1].Kind == tok::r_brace &&
389                                   Changes[i - 1].StartOfTokenColumn == 0;
390     bool WasAlignedWithStartOfNextLine = false;
391     if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
392       unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
393           Changes[i].OriginalWhitespaceRange.getEnd());
394       for (unsigned j = i + 1; j != e; ++j) {
395         if (Changes[j].Kind != tok::comment) { // Skip over comments.
396           unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
397               Changes[j].OriginalWhitespaceRange.getEnd());
398           // The start of the next token was previously aligned with the
399           // start of this comment.
400           WasAlignedWithStartOfNextLine =
401               CommentColumn == NextColumn ||
402               CommentColumn == NextColumn + Style.IndentWidth;
403           break;
404         }
405       }
406     }
407     if (!Style.AlignTrailingComments || FollowsRBraceInColumn0) {
408       alignTrailingComments(StartOfSequence, i, MinColumn);
409       MinColumn = ChangeMinColumn;
410       MaxColumn = ChangeMinColumn;
411       StartOfSequence = i;
412     } else if (BreakBeforeNext || Newlines > 1 ||
413                (ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
414                // Break the comment sequence if the previous line did not end
415                // in a trailing comment.
416                (Changes[i].NewlinesBefore == 1 && i > 0 &&
417                 !Changes[i - 1].IsTrailingComment) ||
418                WasAlignedWithStartOfNextLine) {
419       alignTrailingComments(StartOfSequence, i, MinColumn);
420       MinColumn = ChangeMinColumn;
421       MaxColumn = ChangeMaxColumn;
422       StartOfSequence = i;
423     } else {
424       MinColumn = std::max(MinColumn, ChangeMinColumn);
425       MaxColumn = std::min(MaxColumn, ChangeMaxColumn);
426     }
427     BreakBeforeNext =
428         (i == 0) || (Changes[i].NewlinesBefore > 1) ||
429         // Never start a sequence with a comment at the beginning of
430         // the line.
431         (Changes[i].NewlinesBefore == 1 && StartOfSequence == i);
432     Newlines = 0;
433   }
434   alignTrailingComments(StartOfSequence, Changes.size(), MinColumn);
435 }
436 
437 void WhitespaceManager::alignTrailingComments(unsigned Start, unsigned End,
438                                               unsigned Column) {
439   for (unsigned i = Start; i != End; ++i) {
440     int Shift = 0;
441     if (Changes[i].IsTrailingComment) {
442       Shift = Column - Changes[i].StartOfTokenColumn;
443     }
444     if (Changes[i].StartOfBlockComment) {
445       Shift = Changes[i].IndentationOffset +
446               Changes[i].StartOfBlockComment->StartOfTokenColumn -
447               Changes[i].StartOfTokenColumn;
448     }
449     assert(Shift >= 0);
450     Changes[i].Spaces += Shift;
451     if (i + 1 != End)
452       Changes[i + 1].PreviousEndOfTokenColumn += Shift;
453     Changes[i].StartOfTokenColumn += Shift;
454   }
455 }
456 
457 void WhitespaceManager::alignEscapedNewlines() {
458   unsigned MaxEndOfLine =
459       Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
460   unsigned StartOfMacro = 0;
461   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
462     Change &C = Changes[i];
463     if (C.NewlinesBefore > 0) {
464       if (C.ContinuesPPDirective) {
465         MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, MaxEndOfLine);
466       } else {
467         alignEscapedNewlines(StartOfMacro + 1, i, MaxEndOfLine);
468         MaxEndOfLine = Style.AlignEscapedNewlinesLeft ? 0 : Style.ColumnLimit;
469         StartOfMacro = i;
470       }
471     }
472   }
473   alignEscapedNewlines(StartOfMacro + 1, Changes.size(), MaxEndOfLine);
474 }
475 
476 void WhitespaceManager::alignEscapedNewlines(unsigned Start, unsigned End,
477                                              unsigned Column) {
478   for (unsigned i = Start; i < End; ++i) {
479     Change &C = Changes[i];
480     if (C.NewlinesBefore > 0) {
481       assert(C.ContinuesPPDirective);
482       if (C.PreviousEndOfTokenColumn + 1 > Column)
483         C.EscapedNewlineColumn = 0;
484       else
485         C.EscapedNewlineColumn = Column;
486     }
487   }
488 }
489 
490 void WhitespaceManager::generateChanges() {
491   for (unsigned i = 0, e = Changes.size(); i != e; ++i) {
492     const Change &C = Changes[i];
493     if (i > 0) {
494       assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() !=
495                  C.OriginalWhitespaceRange.getBegin() &&
496              "Generating two replacements for the same location");
497     }
498     if (C.CreateReplacement) {
499       std::string ReplacementText = C.PreviousLinePostfix;
500       if (C.ContinuesPPDirective)
501         appendNewlineText(ReplacementText, C.NewlinesBefore,
502                           C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn);
503       else
504         appendNewlineText(ReplacementText, C.NewlinesBefore);
505       appendIndentText(ReplacementText, C.IndentLevel, std::max(0, C.Spaces),
506                        C.StartOfTokenColumn - std::max(0, C.Spaces));
507       ReplacementText.append(C.CurrentLinePrefix);
508       storeReplacement(C.OriginalWhitespaceRange, ReplacementText);
509     }
510   }
511 }
512 
513 void WhitespaceManager::storeReplacement(SourceRange Range,
514                                          StringRef Text) {
515   unsigned WhitespaceLength = SourceMgr.getFileOffset(Range.getEnd()) -
516                               SourceMgr.getFileOffset(Range.getBegin());
517   // Don't create a replacement, if it does not change anything.
518   if (StringRef(SourceMgr.getCharacterData(Range.getBegin()),
519                 WhitespaceLength) == Text)
520     return;
521   Replaces.insert(tooling::Replacement(
522       SourceMgr, CharSourceRange::getCharRange(Range), Text));
523 }
524 
525 void WhitespaceManager::appendNewlineText(std::string &Text,
526                                           unsigned Newlines) {
527   for (unsigned i = 0; i < Newlines; ++i)
528     Text.append(UseCRLF ? "\r\n" : "\n");
529 }
530 
531 void WhitespaceManager::appendNewlineText(std::string &Text, unsigned Newlines,
532                                           unsigned PreviousEndOfTokenColumn,
533                                           unsigned EscapedNewlineColumn) {
534   if (Newlines > 0) {
535     unsigned Offset =
536         std::min<int>(EscapedNewlineColumn - 1, PreviousEndOfTokenColumn);
537     for (unsigned i = 0; i < Newlines; ++i) {
538       Text.append(EscapedNewlineColumn - Offset - 1, ' ');
539       Text.append(UseCRLF ? "\\\r\n" : "\\\n");
540       Offset = 0;
541     }
542   }
543 }
544 
545 void WhitespaceManager::appendIndentText(std::string &Text,
546                                          unsigned IndentLevel, unsigned Spaces,
547                                          unsigned WhitespaceStartColumn) {
548   switch (Style.UseTab) {
549   case FormatStyle::UT_Never:
550     Text.append(Spaces, ' ');
551     break;
552   case FormatStyle::UT_Always: {
553     unsigned FirstTabWidth =
554         Style.TabWidth - WhitespaceStartColumn % Style.TabWidth;
555     // Indent with tabs only when there's at least one full tab.
556     if (FirstTabWidth + Style.TabWidth <= Spaces) {
557       Spaces -= FirstTabWidth;
558       Text.append("\t");
559     }
560     Text.append(Spaces / Style.TabWidth, '\t');
561     Text.append(Spaces % Style.TabWidth, ' ');
562     break;
563   }
564   case FormatStyle::UT_ForIndentation:
565     if (WhitespaceStartColumn == 0) {
566       unsigned Indentation = IndentLevel * Style.IndentWidth;
567       // This happens, e.g. when a line in a block comment is indented less than
568       // the first one.
569       if (Indentation > Spaces)
570         Indentation = Spaces;
571       unsigned Tabs = Indentation / Style.TabWidth;
572       Text.append(Tabs, '\t');
573       Spaces -= Tabs * Style.TabWidth;
574     }
575     Text.append(Spaces, ' ');
576     break;
577   }
578 }
579 
580 } // namespace format
581 } // namespace clang
582