blob: 957256965f3bce4d9cdbd95b5d841df7614a7463 [file] [log] [blame]
Daniel Jasper0df50932014-12-10 19:00:42 +00001//===--- UnwrappedLineFormatter.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#include "UnwrappedLineFormatter.h"
11#include "WhitespaceManager.h"
12#include "llvm/Support/Debug.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000013#include <queue>
Daniel Jasper0df50932014-12-10 19:00:42 +000014
15#define DEBUG_TYPE "format-formatter"
16
17namespace clang {
18namespace format {
19
20namespace {
21
22bool startsExternCBlock(const AnnotatedLine &Line) {
23 const FormatToken *Next = Line.First->getNextNonComment();
24 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000025 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
Daniel Jasper0df50932014-12-10 19:00:42 +000026 NextNext && NextNext->is(tok::l_brace);
27}
28
Manuel Klimek3d3ea842015-05-12 09:23:57 +000029/// \brief Tracks the indent level of \c AnnotatedLines across levels.
30///
31/// \c nextLine must be called for each \c AnnotatedLine, after which \c
32/// getIndent() will return the indent for the last line \c nextLine was called
33/// with.
34/// If the line is not formatted (and thus the indent does not change), calling
35/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
36/// subsequent lines on the same level to be indented at the same level as the
37/// given line.
38class LevelIndentTracker {
39public:
40 LevelIndentTracker(const FormatStyle &Style,
41 const AdditionalKeywords &Keywords, unsigned StartLevel,
42 int AdditionalIndent)
Daniel Jasper5fc133e2015-05-12 10:16:02 +000043 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000044 for (unsigned i = 0; i != StartLevel; ++i)
45 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
46 }
47
48 /// \brief Returns the indent for the current line.
49 unsigned getIndent() const { return Indent; }
50
51 /// \brief Update the indent state given that \p Line is going to be formatted
52 /// next.
53 void nextLine(const AnnotatedLine &Line) {
54 Offset = getIndentOffset(*Line.First);
Manuel Klimekf0c95b32015-06-11 10:14:13 +000055 // Update the indent level cache size so that we can rely on it
56 // having the right size in adjustToUnmodifiedline.
57 while (IndentForLevel.size() <= Line.Level)
58 IndentForLevel.push_back(-1);
Manuel Klimek3d3ea842015-05-12 09:23:57 +000059 if (Line.InPPDirective) {
Daniel Jasper5fc133e2015-05-12 10:16:02 +000060 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
Manuel Klimek3d3ea842015-05-12 09:23:57 +000061 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000062 IndentForLevel.resize(Line.Level + 1);
63 Indent = getIndent(IndentForLevel, Line.Level);
64 }
65 if (static_cast<int>(Indent) + Offset >= 0)
66 Indent += Offset;
67 }
68
69 /// \brief Update the level indent to adapt to the given \p Line.
70 ///
71 /// When a line is not formatted, we move the subsequent lines on the same
72 /// level to the same indent.
73 /// Note that \c nextLine must have been called before this method.
74 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
75 unsigned LevelIndent = Line.First->OriginalColumn;
76 if (static_cast<int>(LevelIndent) - Offset >= 0)
77 LevelIndent -= Offset;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000078 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
Manuel Klimek3d3ea842015-05-12 09:23:57 +000079 !Line.InPPDirective)
80 IndentForLevel[Line.Level] = LevelIndent;
81 }
82
83private:
84 /// \brief Get the offset of the line relatively to the level.
85 ///
86 /// For example, 'public:' labels in classes are offset by 1 or 2
87 /// characters to the left from their level.
88 int getIndentOffset(const FormatToken &RootToken) {
89 if (Style.Language == FormatStyle::LK_Java ||
90 Style.Language == FormatStyle::LK_JavaScript)
91 return 0;
92 if (RootToken.isAccessSpecifier(false) ||
93 RootToken.isObjCAccessSpecifier() ||
Daniel Jaspera00de632015-12-01 12:05:04 +000094 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
95 RootToken.Next && RootToken.Next->is(tok::colon)))
Manuel Klimek3d3ea842015-05-12 09:23:57 +000096 return Style.AccessModifierOffset;
97 return 0;
98 }
99
100 /// \brief Get the indent of \p Level from \p IndentForLevel.
101 ///
102 /// \p IndentForLevel must contain the indent for the level \c l
103 /// at \p IndentForLevel[l], or a value < 0 if the indent for
104 /// that level is unknown.
105 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
106 if (IndentForLevel[Level] != -1)
107 return IndentForLevel[Level];
108 if (Level == 0)
109 return 0;
110 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
111 }
112
113 const FormatStyle &Style;
114 const AdditionalKeywords &Keywords;
Daniel Jasper56807c12015-05-12 11:14:06 +0000115 const unsigned AdditionalIndent;
Daniel Jasper5fc133e2015-05-12 10:16:02 +0000116
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000117 /// \brief The indent in characters for each level.
118 std::vector<int> IndentForLevel;
119
120 /// \brief Offset of the current line relative to the indent level.
121 ///
122 /// For example, the 'public' keywords is often indented with a negative
123 /// offset.
124 int Offset = 0;
125
126 /// \brief The current line's indent.
127 unsigned Indent = 0;
128};
129
Daniel Jasper0df50932014-12-10 19:00:42 +0000130class LineJoiner {
131public:
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000132 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
133 const SmallVectorImpl<AnnotatedLine *> &Lines)
134 : Style(Style), Keywords(Keywords), End(Lines.end()),
135 Next(Lines.begin()) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000136
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000137 /// \brief Returns the next line, merging multiple lines into one if possible.
138 const AnnotatedLine *getNextMergedLine(bool DryRun,
139 LevelIndentTracker &IndentTracker) {
140 if (Next == End)
141 return nullptr;
142 const AnnotatedLine *Current = *Next;
143 IndentTracker.nextLine(*Current);
144 unsigned MergedLines =
145 tryFitMultipleLinesInOne(IndentTracker.getIndent(), Next, End);
146 if (MergedLines > 0 && Style.ColumnLimit == 0)
147 // Disallow line merging if there is a break at the start of one of the
148 // input lines.
149 for (unsigned i = 0; i < MergedLines; ++i)
150 if (Next[i + 1]->First->NewlinesBefore > 0)
151 MergedLines = 0;
152 if (!DryRun)
153 for (unsigned i = 0; i < MergedLines; ++i)
Cameron Desrochers1991e5d2016-11-15 15:07:07 +0000154 join(*Next[0], *Next[i + 1]);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000155 Next = Next + MergedLines + 1;
156 return Current;
157 }
158
159private:
Daniel Jasper0df50932014-12-10 19:00:42 +0000160 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
161 unsigned
162 tryFitMultipleLinesInOne(unsigned Indent,
163 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
164 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000165 // Can't join the last line with anything.
166 if (I + 1 == E)
167 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000168 // We can never merge stuff if there are trailing line comments.
169 const AnnotatedLine *TheLine = *I;
170 if (TheLine->Last->is(TT_LineComment))
171 return 0;
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000172 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
173 return 0;
174 if (TheLine->InPPDirective &&
175 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
176 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000177
178 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
179 return 0;
180
181 unsigned Limit =
182 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
183 // If we already exceed the column limit, we set 'Limit' to 0. The different
184 // tryMerge..() functions can then decide whether to still do merging.
185 Limit = TheLine->Last->TotalLength > Limit
186 ? 0
187 : Limit - TheLine->Last->TotalLength;
188
Daniel Jasper0df50932014-12-10 19:00:42 +0000189 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
190 // If necessary, change to something smarter.
191 bool MergeShortFunctions =
192 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper20580fd2015-06-11 13:31:45 +0000193 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000194 I[1]->First->is(tok::r_brace)) ||
195 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
196 TheLine->Level != 0);
197
198 if (TheLine->Last->is(TT_FunctionLBrace) &&
199 TheLine->First != TheLine->Last) {
200 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
201 }
202 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000203 return !Style.BraceWrapping.AfterFunction
Daniel Jasper0df50932014-12-10 19:00:42 +0000204 ? tryMergeSimpleBlock(I, E, Limit)
205 : 0;
206 }
207 if (I[1]->First->is(TT_FunctionLBrace) &&
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000208 Style.BraceWrapping.AfterFunction) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000209 if (I[1]->Last->is(TT_LineComment))
210 return 0;
211
212 // Check for Limit <= 2 to account for the " {".
213 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
214 return 0;
215 Limit -= 2;
216
217 unsigned MergedLines = 0;
218 if (MergeShortFunctions) {
219 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
220 // If we managed to merge the block, count the function header, which is
221 // on a separate line.
222 if (MergedLines > 0)
223 ++MergedLines;
224 }
225 return MergedLines;
226 }
227 if (TheLine->First->is(tok::kw_if)) {
228 return Style.AllowShortIfStatementsOnASingleLine
229 ? tryMergeSimpleControlStatement(I, E, Limit)
230 : 0;
231 }
232 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
233 return Style.AllowShortLoopsOnASingleLine
234 ? tryMergeSimpleControlStatement(I, E, Limit)
235 : 0;
236 }
237 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
238 return Style.AllowShortCaseLabelsOnASingleLine
239 ? tryMergeShortCaseLabels(I, E, Limit)
240 : 0;
241 }
242 if (TheLine->InPPDirective &&
243 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
244 return tryMergeSimplePPDirective(I, E, Limit);
245 }
246 return 0;
247 }
248
Daniel Jasper0df50932014-12-10 19:00:42 +0000249 unsigned
250 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
251 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
252 unsigned Limit) {
253 if (Limit == 0)
254 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000255 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
256 return 0;
257 if (1 + I[1]->Last->TotalLength > Limit)
258 return 0;
259 return 1;
260 }
261
262 unsigned tryMergeSimpleControlStatement(
263 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
264 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
265 if (Limit == 0)
266 return 0;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000267 if (Style.BraceWrapping.AfterControlStatement &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000268 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
269 return 0;
270 if (I[1]->InPPDirective != (*I)->InPPDirective ||
271 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
272 return 0;
273 Limit = limitConsideringMacros(I + 1, E, Limit);
274 AnnotatedLine &Line = **I;
275 if (Line.Last->isNot(tok::r_paren))
276 return 0;
277 if (1 + I[1]->Last->TotalLength > Limit)
278 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000279 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
280 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000281 return 0;
282 // Only inline simple if's (no nested if or else).
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000283 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000284 I[2]->First->is(tok::kw_else))
285 return 0;
286 return 1;
287 }
288
Manuel Klimekd3585db2015-05-11 08:21:35 +0000289 unsigned
290 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
291 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
292 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000293 if (Limit == 0 || I + 1 == E ||
294 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
295 return 0;
296 unsigned NumStmts = 0;
297 unsigned Length = 0;
298 bool InPPDirective = I[0]->InPPDirective;
299 for (; NumStmts < 3; ++NumStmts) {
300 if (I + 1 + NumStmts == E)
301 break;
302 const AnnotatedLine *Line = I[1 + NumStmts];
303 if (Line->InPPDirective != InPPDirective)
304 break;
305 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
306 break;
307 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Daniel Jasper368369b2015-09-21 09:50:01 +0000308 tok::kw_while, tok::comment) ||
309 Line->Last->is(tok::comment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000310 return 0;
311 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
312 }
313 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
314 return 0;
315 return NumStmts;
316 }
317
318 unsigned
319 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
320 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
321 unsigned Limit) {
322 AnnotatedLine &Line = **I;
323
324 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000325 // FIXME: If an option to allow short exception handling clauses on a single
326 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000327 if (Style.Language != FormatStyle::LK_Java &&
328 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
329 return 0;
330
331 // Check that the current line allows merging. This depends on whether we
332 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000333 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
334 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000335 return 0;
336 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000337 tok::kw___try, tok::kw_catch, tok::kw___finally,
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000338 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000339 if (!Style.AllowShortBlocksOnASingleLine)
340 return 0;
341 if (!Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000342 Line.startsWith(tok::kw_if))
Daniel Jasper0df50932014-12-10 19:00:42 +0000343 return 0;
344 if (!Style.AllowShortLoopsOnASingleLine &&
345 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
346 return 0;
347 // FIXME: Consider an option to allow short exception handling clauses on
348 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000349 // FIXME: This isn't covered by tests.
350 // FIXME: For catch, __except, __finally the first token on the line
351 // is '}', so this isn't correct here.
352 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
353 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000354 return 0;
355 }
356
357 FormatToken *Tok = I[1]->First;
358 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
359 (Tok->getNextNonComment() == nullptr ||
360 Tok->getNextNonComment()->is(tok::semi))) {
361 // We merge empty blocks even if the line exceeds the column limit.
362 Tok->SpacesRequiredBefore = 0;
363 Tok->CanBreakBefore = true;
364 return 1;
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000365 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000366 !startsExternCBlock(Line)) {
367 // We don't merge short records.
Daniel Jasper29647492015-05-05 08:12:50 +0000368 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
369 Keywords.kw_interface))
Daniel Jasper0df50932014-12-10 19:00:42 +0000370 return 0;
371
372 // Check that we still have three lines and they fit into the limit.
373 if (I + 2 == E || I[2]->Type == LT_Invalid)
374 return 0;
375 Limit = limitConsideringMacros(I + 2, E, Limit);
376
377 if (!nextTwoLinesFitInto(I, Limit))
378 return 0;
379
380 // Second, check that the next line does not contain any braces - if it
381 // does, readability declines when putting it into a single line.
382 if (I[1]->Last->is(TT_LineComment))
383 return 0;
384 do {
385 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
386 return 0;
387 Tok = Tok->Next;
388 } while (Tok);
389
390 // Last, check that the third line starts with a closing brace.
391 Tok = I[2]->First;
392 if (Tok->isNot(tok::r_brace))
393 return 0;
394
Daniel Jaspere9f53572015-04-30 09:24:17 +0000395 // Don't merge "if (a) { .. } else {".
396 if (Tok->Next && Tok->Next->is(tok::kw_else))
397 return 0;
398
Daniel Jasper0df50932014-12-10 19:00:42 +0000399 return 2;
400 }
401 return 0;
402 }
403
404 /// Returns the modified column limit for \p I if it is inside a macro and
405 /// needs a trailing '\'.
406 unsigned
407 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
408 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
409 unsigned Limit) {
410 if (I[0]->InPPDirective && I + 1 != E &&
411 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
412 return Limit < 2 ? 0 : Limit - 2;
413 }
414 return Limit;
415 }
416
417 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
418 unsigned Limit) {
419 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
420 return false;
421 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
422 }
423
424 bool containsMustBreak(const AnnotatedLine *Line) {
425 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
426 if (Tok->MustBreakBefore)
427 return true;
428 }
429 return false;
430 }
431
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000432 void join(AnnotatedLine &A, const AnnotatedLine &B) {
433 assert(!A.Last->Next);
434 assert(!B.First->Previous);
435 if (B.Affected)
436 A.Affected = true;
437 A.Last->Next = B.First;
438 B.First->Previous = A.Last;
439 B.First->CanBreakBefore = true;
440 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
441 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
442 Tok->TotalLength += LengthA;
443 A.Last = Tok;
444 }
445 }
446
Daniel Jasper0df50932014-12-10 19:00:42 +0000447 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000448 const AdditionalKeywords &Keywords;
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000449 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000450
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000451 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
Daniel Jasper0df50932014-12-10 19:00:42 +0000452};
453
Daniel Jasperd1c13732015-01-23 19:37:25 +0000454static void markFinalized(FormatToken *Tok) {
455 for (; Tok; Tok = Tok->Next) {
456 Tok->Finalized = true;
457 for (AnnotatedLine *Child : Tok->Children)
458 markFinalized(Child->First);
459 }
460}
461
Manuel Klimekd3585db2015-05-11 08:21:35 +0000462#ifndef NDEBUG
463static void printLineState(const LineState &State) {
464 llvm::dbgs() << "State: ";
465 for (const ParenState &P : State.Stack) {
466 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
467 << " ";
468 }
469 llvm::dbgs() << State.NextToken->TokenText << "\n";
470}
471#endif
472
473/// \brief Base class for classes that format one \c AnnotatedLine.
474class LineFormatter {
475public:
476 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
477 const FormatStyle &Style,
478 UnwrappedLineFormatter *BlockFormatter)
479 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
480 BlockFormatter(BlockFormatter) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000481 virtual ~LineFormatter() {}
Manuel Klimekd3585db2015-05-11 08:21:35 +0000482
483 /// \brief Formats an \c AnnotatedLine and returns the penalty.
484 ///
485 /// If \p DryRun is \c false, directly applies the changes.
486 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
487 bool DryRun) = 0;
488
489protected:
490 /// \brief If the \p State's next token is an r_brace closing a nested block,
491 /// format the nested block before it.
492 ///
493 /// Returns \c true if all children could be placed successfully and adapts
494 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
495 /// creates changes using \c Whitespaces.
496 ///
497 /// The crucial idea here is that children always get formatted upon
498 /// encountering the closing brace right after the nested block. Now, if we
499 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
500 /// \c false), the entire block has to be kept on the same line (which is only
501 /// possible if it fits on the line, only contains a single statement, etc.
502 ///
503 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
504 /// break after the "{", format all lines with correct indentation and the put
505 /// the closing "}" on yet another new line.
506 ///
507 /// This enables us to keep the simple structure of the
508 /// \c UnwrappedLineFormatter, where we only have two options for each token:
509 /// break or don't break.
510 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
511 unsigned &Penalty) {
512 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
513 FormatToken &Previous = *State.NextToken->Previous;
514 if (!LBrace || LBrace->isNot(tok::l_brace) ||
515 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
516 // The previous token does not open a block. Nothing to do. We don't
517 // assert so that we can simply call this function for all tokens.
518 return true;
519
520 if (NewLine) {
521 int AdditionalIndent = State.Stack.back().Indent -
522 Previous.Children[0]->Level * Style.IndentWidth;
523
524 Penalty +=
525 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
526 /*FixBadIndentation=*/true);
527 return true;
528 }
529
530 if (Previous.Children[0]->First->MustBreakBefore)
531 return false;
532
Manuel Klimekd3585db2015-05-11 08:21:35 +0000533 // Cannot merge into one line if this line ends on a comment.
534 if (Previous.is(tok::comment))
535 return false;
536
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000537 // Cannot merge multiple statements into a single line.
538 if (Previous.Children.size() > 1)
539 return false;
540
541 const AnnotatedLine *Child = Previous.Children[0];
Manuel Klimekd3585db2015-05-11 08:21:35 +0000542 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000543 if (Child->Last->isTrailingComment())
Manuel Klimekd3585db2015-05-11 08:21:35 +0000544 return false;
545
546 // If the child line exceeds the column limit, we wouldn't want to merge it.
547 // We add +2 for the trailing " }".
548 if (Style.ColumnLimit > 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000549 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000550 return false;
551
552 if (!DryRun) {
553 Whitespaces->replaceWhitespace(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000554 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000555 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
556 }
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000557 Penalty += formatLine(*Child, State.Column + 1, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000558
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000559 State.Column += 1 + Child->Last->TotalLength;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000560 return true;
561 }
562
563 ContinuationIndenter *Indenter;
564
565private:
566 WhitespaceManager *Whitespaces;
567 const FormatStyle &Style;
568 UnwrappedLineFormatter *BlockFormatter;
569};
570
571/// \brief Formatter that keeps the existing line breaks.
572class NoColumnLimitLineFormatter : public LineFormatter {
573public:
574 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
575 WhitespaceManager *Whitespaces,
576 const FormatStyle &Style,
577 UnwrappedLineFormatter *BlockFormatter)
578 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
579
580 /// \brief Formats the line, simply keeping all of the input's line breaking
581 /// decisions.
582 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
583 bool DryRun) override {
584 assert(!DryRun);
585 LineState State =
586 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
587 while (State.NextToken) {
588 bool Newline =
589 Indenter->mustBreak(State) ||
590 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
591 unsigned Penalty = 0;
592 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
593 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
594 }
595 return 0;
596 }
597};
598
599/// \brief Formatter that puts all tokens into a single line without breaks.
600class NoLineBreakFormatter : public LineFormatter {
601public:
602 NoLineBreakFormatter(ContinuationIndenter *Indenter,
603 WhitespaceManager *Whitespaces, const FormatStyle &Style,
604 UnwrappedLineFormatter *BlockFormatter)
605 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
606
607 /// \brief Puts all tokens into a single line.
608 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Hans Wennborg7eb54642015-09-10 17:07:54 +0000609 bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000610 unsigned Penalty = 0;
611 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
612 while (State.NextToken) {
613 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
614 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
615 }
616 return Penalty;
617 }
618};
619
620/// \brief Finds the best way to break lines.
621class OptimizingLineFormatter : public LineFormatter {
622public:
623 OptimizingLineFormatter(ContinuationIndenter *Indenter,
624 WhitespaceManager *Whitespaces,
625 const FormatStyle &Style,
626 UnwrappedLineFormatter *BlockFormatter)
627 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
628
629 /// \brief Formats the line by finding the best line breaks with line lengths
630 /// below the column limit.
631 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Hans Wennborg7eb54642015-09-10 17:07:54 +0000632 bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000633 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
634
635 // If the ObjC method declaration does not fit on a line, we should format
636 // it with one arg per line.
637 if (State.Line->Type == LT_ObjCMethodDecl)
638 State.Stack.back().BreakBeforeParameter = true;
639
640 // Find best solution in solution space.
641 return analyzeSolutionSpace(State, DryRun);
642 }
643
644private:
645 struct CompareLineStatePointers {
646 bool operator()(LineState *obj1, LineState *obj2) const {
647 return *obj1 < *obj2;
648 }
649 };
650
651 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
652 ///
653 /// In case of equal penalties, we want to prefer states that were inserted
654 /// first. During state generation we make sure that we insert states first
655 /// that break the line as late as possible.
656 typedef std::pair<unsigned, unsigned> OrderedPenalty;
657
658 /// \brief An edge in the solution space from \c Previous->State to \c State,
659 /// inserting a newline dependent on the \c NewLine.
660 struct StateNode {
661 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
662 : State(State), NewLine(NewLine), Previous(Previous) {}
663 LineState State;
664 bool NewLine;
665 StateNode *Previous;
666 };
667
668 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
669 /// \c State has the given \c OrderedPenalty.
670 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
671
672 /// \brief The BFS queue type.
673 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
674 std::greater<QueueItem>> QueueType;
675
676 /// \brief Analyze the entire solution space starting from \p InitialState.
677 ///
678 /// This implements a variant of Dijkstra's algorithm on the graph that spans
679 /// the solution space (\c LineStates are the nodes). The algorithm tries to
680 /// find the shortest path (the one with lowest penalty) from \p InitialState
681 /// to a state where all tokens are placed. Returns the penalty.
682 ///
683 /// If \p DryRun is \c false, directly applies the changes.
684 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
685 std::set<LineState *, CompareLineStatePointers> Seen;
686
687 // Increasing count of \c StateNode items we have created. This is used to
688 // create a deterministic order independent of the container.
689 unsigned Count = 0;
690 QueueType Queue;
691
692 // Insert start element into queue.
693 StateNode *Node =
694 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
695 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
696 ++Count;
697
698 unsigned Penalty = 0;
699
700 // While not empty, take first element and follow edges.
701 while (!Queue.empty()) {
702 Penalty = Queue.top().first.first;
703 StateNode *Node = Queue.top().second;
704 if (!Node->State.NextToken) {
705 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
706 break;
707 }
708 Queue.pop();
709
710 // Cut off the analysis of certain solutions if the analysis gets too
711 // complex. See description of IgnoreStackForComparison.
Daniel Jasper75bf2032015-10-27 22:55:55 +0000712 if (Count > 50000)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000713 Node->State.IgnoreStackForComparison = true;
714
715 if (!Seen.insert(&Node->State).second)
716 // State already examined with lower penalty.
717 continue;
718
719 FormatDecision LastFormat = Node->State.NextToken->Decision;
720 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
721 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
722 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
723 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
724 }
725
726 if (Queue.empty()) {
727 // We were unable to find a solution, do nothing.
728 // FIXME: Add diagnostic?
729 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
730 return 0;
731 }
732
733 // Reconstruct the solution.
734 if (!DryRun)
735 reconstructPath(InitialState, Queue.top().second);
736
737 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
738 DEBUG(llvm::dbgs() << "---\n");
739
740 return Penalty;
741 }
742
743 /// \brief Add the following state to the analysis queue \c Queue.
744 ///
745 /// Assume the current state is \p PreviousNode and has been reached with a
746 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
747 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
748 bool NewLine, unsigned *Count, QueueType *Queue) {
749 if (NewLine && !Indenter->canBreak(PreviousNode->State))
750 return;
751 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
752 return;
753
754 StateNode *Node = new (Allocator.Allocate())
755 StateNode(PreviousNode->State, NewLine, PreviousNode);
756 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
757 return;
758
759 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
760
761 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
762 ++(*Count);
763 }
764
765 /// \brief Applies the best formatting by reconstructing the path in the
766 /// solution space that leads to \c Best.
767 void reconstructPath(LineState &State, StateNode *Best) {
768 std::deque<StateNode *> Path;
769 // We do not need a break before the initial token.
770 while (Best->Previous) {
771 Path.push_front(Best);
772 Best = Best->Previous;
773 }
774 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
775 I != E; ++I) {
776 unsigned Penalty = 0;
777 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
778 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
779
780 DEBUG({
781 printLineState((*I)->Previous->State);
782 if ((*I)->NewLine) {
783 llvm::dbgs() << "Penalty for placing "
784 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
785 << Penalty << "\n";
786 }
787 });
788 }
789 }
790
791 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
792};
793
Hans Wennborg7eb54642015-09-10 17:07:54 +0000794} // anonymous namespace
Daniel Jasper0df50932014-12-10 19:00:42 +0000795
796unsigned
797UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
798 bool DryRun, int AdditionalIndent,
799 bool FixBadIndentation) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000800 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +0000801
802 // Try to look up already computed penalty in DryRun-mode.
803 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
804 &Lines, AdditionalIndent);
805 auto CacheIt = PenaltyCache.find(CacheKey);
806 if (DryRun && CacheIt != PenaltyCache.end())
807 return CacheIt->second;
808
809 assert(!Lines.empty());
810 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000811 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
812 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000813 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000814 const AnnotatedLine *NextLine = nullptr;
Daniel Jasperf67c3242015-11-01 00:27:35 +0000815
816 // The minimum level of consecutive lines that have been formatted.
817 unsigned RangeMinLevel = UINT_MAX;
Daniel Jasperf67c3242015-11-01 00:27:35 +0000818
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000819 for (const AnnotatedLine *Line =
820 Joiner.getNextMergedLine(DryRun, IndentTracker);
821 Line; Line = NextLine) {
822 const AnnotatedLine &TheLine = *Line;
823 unsigned Indent = IndentTracker.getIndent();
Daniel Jasperf67c3242015-11-01 00:27:35 +0000824
825 // We continue formatting unchanged lines to adjust their indent, e.g. if a
826 // scope was added. However, we need to carefully stop doing this when we
827 // exit the scope of affected lines to prevent indenting a the entire
828 // remaining file if it currently missing a closing brace.
829 bool ContinueFormatting =
830 TheLine.Level > RangeMinLevel ||
Daniel Jasperf83834f2015-11-02 20:02:49 +0000831 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
Daniel Jasperf67c3242015-11-01 00:27:35 +0000832
833 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Daniel Jaspera1036e52015-10-28 01:08:22 +0000834 Indent != TheLine.First->OriginalColumn;
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000835 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000836 // We cannot format this line; if the reason is that the line had a
837 // parsing error, remember that.
838 if (ShouldFormat && TheLine.Type == LT_Invalid && IncompleteFormat)
839 *IncompleteFormat = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000840
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000841 if (ShouldFormat && TheLine.Type != LT_Invalid) {
842 if (!DryRun)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000843 formatFirstToken(TheLine, PreviousLine, Indent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000844
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000845 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
846 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
847 bool FitsIntoOneLine =
848 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
Martin Probst0cd74ee2016-06-13 16:39:50 +0000849 (TheLine.Type == LT_ImportStatement &&
850 (Style.Language != FormatStyle::LK_JavaScript ||
851 !Style.JavaScriptWrapImports));
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000852
853 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000854 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
855 .formatLine(TheLine, Indent, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000856 else if (FitsIntoOneLine)
857 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
858 .formatLine(TheLine, Indent, DryRun);
859 else
Manuel Klimekd3585db2015-05-11 08:21:35 +0000860 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
861 .formatLine(TheLine, Indent, DryRun);
Daniel Jasperf67c3242015-11-01 00:27:35 +0000862 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
Daniel Jasper0df50932014-12-10 19:00:42 +0000863 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000864 // If no token in the current line is affected, we still need to format
865 // affected children.
866 if (TheLine.ChildrenAffected)
Daniel Jasper35ca66d2016-02-29 12:26:20 +0000867 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
868 if (!Tok->Children.empty())
869 format(Tok->Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000870
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000871 // Adapt following lines on the current indent level to the same level
872 // unless the current \c AnnotatedLine is not at the beginning of a line.
873 bool StartsNewLine =
874 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
875 if (StartsNewLine)
876 IndentTracker.adjustToUnmodifiedLine(TheLine);
877 if (!DryRun) {
878 bool ReformatLeadingWhitespace =
879 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
880 TheLine.LeadingEmptyLinesAffected);
881 // Format the first token.
882 if (ReformatLeadingWhitespace)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000883 formatFirstToken(TheLine, PreviousLine,
884 TheLine.First->OriginalColumn);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000885 else
886 Whitespaces->addUntouchableToken(*TheLine.First,
887 TheLine.InPPDirective);
888
889 // Notify the WhitespaceManager about the unchanged whitespace.
890 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +0000891 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +0000892 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000893 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasperf67c3242015-11-01 00:27:35 +0000894 RangeMinLevel = UINT_MAX;
Daniel Jasper0df50932014-12-10 19:00:42 +0000895 }
Daniel Jasperd1c13732015-01-23 19:37:25 +0000896 if (!DryRun)
897 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000898 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +0000899 }
900 PenaltyCache[CacheKey] = Penalty;
901 return Penalty;
902}
903
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000904void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
Daniel Jasper0df50932014-12-10 19:00:42 +0000905 const AnnotatedLine *PreviousLine,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000906 unsigned Indent) {
907 FormatToken& RootToken = *Line.First;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000908 if (RootToken.is(tok::eof)) {
909 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000910 Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0,
911 /*TargetColumn=*/0);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000912 return;
913 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000914 unsigned Newlines =
915 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
916 // Remove empty lines before "}" where applicable.
917 if (RootToken.is(tok::r_brace) &&
918 (!RootToken.Next ||
919 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
920 Newlines = std::min(Newlines, 1u);
921 if (Newlines == 0 && !RootToken.IsFirst)
922 Newlines = 1;
923 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
924 Newlines = 0;
925
926 // Remove empty lines after "{".
927 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
928 PreviousLine->Last->is(tok::l_brace) &&
929 PreviousLine->First->isNot(tok::kw_namespace) &&
930 !startsExternCBlock(*PreviousLine))
931 Newlines = 1;
932
933 // Insert extra new line before access specifiers.
934 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
935 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
936 ++Newlines;
937
938 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +0000939 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
940 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +0000941 Newlines = std::min(1u, Newlines);
942
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000943 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
944 Line.InPPDirective &&
945 !RootToken.HasUnescapedNewline);
Daniel Jasper0df50932014-12-10 19:00:42 +0000946}
947
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000948unsigned
949UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
950 const AnnotatedLine *NextLine) const {
951 // In preprocessor directives reserve two chars for trailing " \" if the
952 // next line continues the preprocessor directive.
953 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +0000954 InPPDirective &&
955 // If there is no next line, this is likely a child line and the parent
956 // continues the preprocessor directive.
957 (!NextLine ||
958 (NextLine->InPPDirective &&
959 // If there is an unescaped newline between this line and the next, the
960 // next line starts a new preprocessor directive.
961 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000962 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +0000963}
964
Daniel Jasper0df50932014-12-10 19:00:42 +0000965} // namespace format
966} // namespace clang