blob: eb8de6598ebb853b7b0f4e04a29d3a10663c9fec [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
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000189 if (TheLine->Last->is(TT_FunctionLBrace) &&
190 TheLine->First == TheLine->Last &&
191 !Style.BraceWrapping.SplitEmptyFunctionBody &&
192 I[1]->First->is(tok::r_brace))
193 return tryMergeSimpleBlock(I, E, Limit);
194
Daniel Jasper0df50932014-12-10 19:00:42 +0000195 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
196 // If necessary, change to something smarter.
197 bool MergeShortFunctions =
198 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper20580fd2015-06-11 13:31:45 +0000199 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000200 I[1]->First->is(tok::r_brace)) ||
201 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
202 TheLine->Level != 0);
203
204 if (TheLine->Last->is(TT_FunctionLBrace) &&
205 TheLine->First != TheLine->Last) {
206 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
207 }
208 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000209 return !Style.BraceWrapping.AfterFunction
Daniel Jasper0df50932014-12-10 19:00:42 +0000210 ? tryMergeSimpleBlock(I, E, Limit)
211 : 0;
212 }
213 if (I[1]->First->is(TT_FunctionLBrace) &&
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000214 Style.BraceWrapping.AfterFunction) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000215 if (I[1]->Last->is(TT_LineComment))
216 return 0;
217
218 // Check for Limit <= 2 to account for the " {".
219 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
220 return 0;
221 Limit -= 2;
222
223 unsigned MergedLines = 0;
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000224 if (MergeShortFunctions ||
225 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
226 I[1]->First == I[1]->Last && I + 2 != E &&
227 I[2]->First->is(tok::r_brace))) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000228 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
229 // If we managed to merge the block, count the function header, which is
230 // on a separate line.
231 if (MergedLines > 0)
232 ++MergedLines;
233 }
234 return MergedLines;
235 }
236 if (TheLine->First->is(tok::kw_if)) {
237 return Style.AllowShortIfStatementsOnASingleLine
238 ? tryMergeSimpleControlStatement(I, E, Limit)
239 : 0;
240 }
241 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
242 return Style.AllowShortLoopsOnASingleLine
243 ? tryMergeSimpleControlStatement(I, E, Limit)
244 : 0;
245 }
246 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
247 return Style.AllowShortCaseLabelsOnASingleLine
248 ? tryMergeShortCaseLabels(I, E, Limit)
249 : 0;
250 }
251 if (TheLine->InPPDirective &&
252 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
253 return tryMergeSimplePPDirective(I, E, Limit);
254 }
255 return 0;
256 }
257
Daniel Jasper0df50932014-12-10 19:00:42 +0000258 unsigned
259 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
260 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
261 unsigned Limit) {
262 if (Limit == 0)
263 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000264 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
265 return 0;
266 if (1 + I[1]->Last->TotalLength > Limit)
267 return 0;
268 return 1;
269 }
270
271 unsigned tryMergeSimpleControlStatement(
272 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
273 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
274 if (Limit == 0)
275 return 0;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000276 if (Style.BraceWrapping.AfterControlStatement &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000277 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
278 return 0;
279 if (I[1]->InPPDirective != (*I)->InPPDirective ||
280 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
281 return 0;
282 Limit = limitConsideringMacros(I + 1, E, Limit);
283 AnnotatedLine &Line = **I;
284 if (Line.Last->isNot(tok::r_paren))
285 return 0;
286 if (1 + I[1]->Last->TotalLength > Limit)
287 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000288 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
289 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000290 return 0;
291 // Only inline simple if's (no nested if or else).
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000292 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000293 I[2]->First->is(tok::kw_else))
294 return 0;
295 return 1;
296 }
297
Manuel Klimekd3585db2015-05-11 08:21:35 +0000298 unsigned
299 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
300 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
301 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000302 if (Limit == 0 || I + 1 == E ||
303 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
304 return 0;
305 unsigned NumStmts = 0;
306 unsigned Length = 0;
307 bool InPPDirective = I[0]->InPPDirective;
308 for (; NumStmts < 3; ++NumStmts) {
309 if (I + 1 + NumStmts == E)
310 break;
311 const AnnotatedLine *Line = I[1 + NumStmts];
312 if (Line->InPPDirective != InPPDirective)
313 break;
314 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
315 break;
316 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Daniel Jasper368369b2015-09-21 09:50:01 +0000317 tok::kw_while, tok::comment) ||
318 Line->Last->is(tok::comment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000319 return 0;
320 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
321 }
322 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
323 return 0;
324 return NumStmts;
325 }
326
327 unsigned
328 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
329 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
330 unsigned Limit) {
331 AnnotatedLine &Line = **I;
332
333 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000334 // FIXME: If an option to allow short exception handling clauses on a single
335 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000336 if (Style.Language != FormatStyle::LK_Java &&
337 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
338 return 0;
339
340 // Check that the current line allows merging. This depends on whether we
341 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000342 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
343 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000344 return 0;
345 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000346 tok::kw___try, tok::kw_catch, tok::kw___finally,
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000347 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000348 if (!Style.AllowShortBlocksOnASingleLine)
349 return 0;
350 if (!Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000351 Line.startsWith(tok::kw_if))
Daniel Jasper0df50932014-12-10 19:00:42 +0000352 return 0;
353 if (!Style.AllowShortLoopsOnASingleLine &&
354 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
355 return 0;
356 // FIXME: Consider an option to allow short exception handling clauses on
357 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000358 // FIXME: This isn't covered by tests.
359 // FIXME: For catch, __except, __finally the first token on the line
360 // is '}', so this isn't correct here.
361 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
362 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000363 return 0;
364 }
365
366 FormatToken *Tok = I[1]->First;
367 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
368 (Tok->getNextNonComment() == nullptr ||
369 Tok->getNextNonComment()->is(tok::semi))) {
370 // We merge empty blocks even if the line exceeds the column limit.
371 Tok->SpacesRequiredBefore = 0;
372 Tok->CanBreakBefore = true;
373 return 1;
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000374 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000375 !startsExternCBlock(Line)) {
376 // We don't merge short records.
Daniel Jasper29647492015-05-05 08:12:50 +0000377 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
378 Keywords.kw_interface))
Daniel Jasper0df50932014-12-10 19:00:42 +0000379 return 0;
380
381 // Check that we still have three lines and they fit into the limit.
382 if (I + 2 == E || I[2]->Type == LT_Invalid)
383 return 0;
384 Limit = limitConsideringMacros(I + 2, E, Limit);
385
386 if (!nextTwoLinesFitInto(I, Limit))
387 return 0;
388
389 // Second, check that the next line does not contain any braces - if it
390 // does, readability declines when putting it into a single line.
391 if (I[1]->Last->is(TT_LineComment))
392 return 0;
393 do {
394 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
395 return 0;
396 Tok = Tok->Next;
397 } while (Tok);
398
399 // Last, check that the third line starts with a closing brace.
400 Tok = I[2]->First;
401 if (Tok->isNot(tok::r_brace))
402 return 0;
403
Daniel Jaspere9f53572015-04-30 09:24:17 +0000404 // Don't merge "if (a) { .. } else {".
405 if (Tok->Next && Tok->Next->is(tok::kw_else))
406 return 0;
407
Daniel Jasper0df50932014-12-10 19:00:42 +0000408 return 2;
409 }
410 return 0;
411 }
412
413 /// Returns the modified column limit for \p I if it is inside a macro and
414 /// needs a trailing '\'.
415 unsigned
416 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
417 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
418 unsigned Limit) {
419 if (I[0]->InPPDirective && I + 1 != E &&
420 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
421 return Limit < 2 ? 0 : Limit - 2;
422 }
423 return Limit;
424 }
425
426 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
427 unsigned Limit) {
428 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
429 return false;
430 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
431 }
432
433 bool containsMustBreak(const AnnotatedLine *Line) {
434 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
435 if (Tok->MustBreakBefore)
436 return true;
437 }
438 return false;
439 }
440
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000441 void join(AnnotatedLine &A, const AnnotatedLine &B) {
442 assert(!A.Last->Next);
443 assert(!B.First->Previous);
444 if (B.Affected)
445 A.Affected = true;
446 A.Last->Next = B.First;
447 B.First->Previous = A.Last;
448 B.First->CanBreakBefore = true;
449 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
450 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
451 Tok->TotalLength += LengthA;
452 A.Last = Tok;
453 }
454 }
455
Daniel Jasper0df50932014-12-10 19:00:42 +0000456 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000457 const AdditionalKeywords &Keywords;
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000458 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000459
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000460 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
Daniel Jasper0df50932014-12-10 19:00:42 +0000461};
462
Daniel Jasperd1c13732015-01-23 19:37:25 +0000463static void markFinalized(FormatToken *Tok) {
464 for (; Tok; Tok = Tok->Next) {
465 Tok->Finalized = true;
466 for (AnnotatedLine *Child : Tok->Children)
467 markFinalized(Child->First);
468 }
469}
470
Manuel Klimekd3585db2015-05-11 08:21:35 +0000471#ifndef NDEBUG
472static void printLineState(const LineState &State) {
473 llvm::dbgs() << "State: ";
474 for (const ParenState &P : State.Stack) {
475 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
476 << " ";
477 }
478 llvm::dbgs() << State.NextToken->TokenText << "\n";
479}
480#endif
481
482/// \brief Base class for classes that format one \c AnnotatedLine.
483class LineFormatter {
484public:
485 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
486 const FormatStyle &Style,
487 UnwrappedLineFormatter *BlockFormatter)
488 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
489 BlockFormatter(BlockFormatter) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000490 virtual ~LineFormatter() {}
Manuel Klimekd3585db2015-05-11 08:21:35 +0000491
492 /// \brief Formats an \c AnnotatedLine and returns the penalty.
493 ///
494 /// If \p DryRun is \c false, directly applies the changes.
495 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
496 bool DryRun) = 0;
497
498protected:
499 /// \brief If the \p State's next token is an r_brace closing a nested block,
500 /// format the nested block before it.
501 ///
502 /// Returns \c true if all children could be placed successfully and adapts
503 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
504 /// creates changes using \c Whitespaces.
505 ///
506 /// The crucial idea here is that children always get formatted upon
507 /// encountering the closing brace right after the nested block. Now, if we
508 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
509 /// \c false), the entire block has to be kept on the same line (which is only
510 /// possible if it fits on the line, only contains a single statement, etc.
511 ///
512 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
513 /// break after the "{", format all lines with correct indentation and the put
514 /// the closing "}" on yet another new line.
515 ///
516 /// This enables us to keep the simple structure of the
517 /// \c UnwrappedLineFormatter, where we only have two options for each token:
518 /// break or don't break.
519 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
520 unsigned &Penalty) {
521 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
522 FormatToken &Previous = *State.NextToken->Previous;
523 if (!LBrace || LBrace->isNot(tok::l_brace) ||
524 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
525 // The previous token does not open a block. Nothing to do. We don't
526 // assert so that we can simply call this function for all tokens.
527 return true;
528
529 if (NewLine) {
530 int AdditionalIndent = State.Stack.back().Indent -
531 Previous.Children[0]->Level * Style.IndentWidth;
532
533 Penalty +=
534 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
535 /*FixBadIndentation=*/true);
536 return true;
537 }
538
539 if (Previous.Children[0]->First->MustBreakBefore)
540 return false;
541
Manuel Klimekd3585db2015-05-11 08:21:35 +0000542 // Cannot merge into one line if this line ends on a comment.
543 if (Previous.is(tok::comment))
544 return false;
545
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000546 // Cannot merge multiple statements into a single line.
547 if (Previous.Children.size() > 1)
548 return false;
549
550 const AnnotatedLine *Child = Previous.Children[0];
Manuel Klimekd3585db2015-05-11 08:21:35 +0000551 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000552 if (Child->Last->isTrailingComment())
Manuel Klimekd3585db2015-05-11 08:21:35 +0000553 return false;
554
555 // If the child line exceeds the column limit, we wouldn't want to merge it.
556 // We add +2 for the trailing " }".
557 if (Style.ColumnLimit > 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000558 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000559 return false;
560
561 if (!DryRun) {
562 Whitespaces->replaceWhitespace(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000563 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000564 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
565 }
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000566 Penalty += formatLine(*Child, State.Column + 1, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000567
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000568 State.Column += 1 + Child->Last->TotalLength;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000569 return true;
570 }
571
572 ContinuationIndenter *Indenter;
573
574private:
575 WhitespaceManager *Whitespaces;
576 const FormatStyle &Style;
577 UnwrappedLineFormatter *BlockFormatter;
578};
579
580/// \brief Formatter that keeps the existing line breaks.
581class NoColumnLimitLineFormatter : public LineFormatter {
582public:
583 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
584 WhitespaceManager *Whitespaces,
585 const FormatStyle &Style,
586 UnwrappedLineFormatter *BlockFormatter)
587 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
588
589 /// \brief Formats the line, simply keeping all of the input's line breaking
590 /// decisions.
591 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
592 bool DryRun) override {
593 assert(!DryRun);
594 LineState State =
595 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
596 while (State.NextToken) {
597 bool Newline =
598 Indenter->mustBreak(State) ||
599 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
600 unsigned Penalty = 0;
601 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
602 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
603 }
604 return 0;
605 }
606};
607
608/// \brief Formatter that puts all tokens into a single line without breaks.
609class NoLineBreakFormatter : public LineFormatter {
610public:
611 NoLineBreakFormatter(ContinuationIndenter *Indenter,
612 WhitespaceManager *Whitespaces, const FormatStyle &Style,
613 UnwrappedLineFormatter *BlockFormatter)
614 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
615
616 /// \brief Puts all tokens into a single line.
617 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Hans Wennborg7eb54642015-09-10 17:07:54 +0000618 bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000619 unsigned Penalty = 0;
620 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
621 while (State.NextToken) {
622 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
Krasimir Georgiev994b6c92017-05-18 08:07:52 +0000623 Indenter->addTokenToState(
624 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000625 }
626 return Penalty;
627 }
628};
629
630/// \brief Finds the best way to break lines.
631class OptimizingLineFormatter : public LineFormatter {
632public:
633 OptimizingLineFormatter(ContinuationIndenter *Indenter,
634 WhitespaceManager *Whitespaces,
635 const FormatStyle &Style,
636 UnwrappedLineFormatter *BlockFormatter)
637 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
638
639 /// \brief Formats the line by finding the best line breaks with line lengths
640 /// below the column limit.
641 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Hans Wennborg7eb54642015-09-10 17:07:54 +0000642 bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000643 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
644
645 // If the ObjC method declaration does not fit on a line, we should format
646 // it with one arg per line.
647 if (State.Line->Type == LT_ObjCMethodDecl)
648 State.Stack.back().BreakBeforeParameter = true;
649
650 // Find best solution in solution space.
651 return analyzeSolutionSpace(State, DryRun);
652 }
653
654private:
655 struct CompareLineStatePointers {
656 bool operator()(LineState *obj1, LineState *obj2) const {
657 return *obj1 < *obj2;
658 }
659 };
660
661 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
662 ///
663 /// In case of equal penalties, we want to prefer states that were inserted
664 /// first. During state generation we make sure that we insert states first
665 /// that break the line as late as possible.
666 typedef std::pair<unsigned, unsigned> OrderedPenalty;
667
668 /// \brief An edge in the solution space from \c Previous->State to \c State,
669 /// inserting a newline dependent on the \c NewLine.
670 struct StateNode {
671 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
672 : State(State), NewLine(NewLine), Previous(Previous) {}
673 LineState State;
674 bool NewLine;
675 StateNode *Previous;
676 };
677
678 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
679 /// \c State has the given \c OrderedPenalty.
680 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
681
682 /// \brief The BFS queue type.
683 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
684 std::greater<QueueItem>> QueueType;
685
686 /// \brief Analyze the entire solution space starting from \p InitialState.
687 ///
688 /// This implements a variant of Dijkstra's algorithm on the graph that spans
689 /// the solution space (\c LineStates are the nodes). The algorithm tries to
690 /// find the shortest path (the one with lowest penalty) from \p InitialState
691 /// to a state where all tokens are placed. Returns the penalty.
692 ///
693 /// If \p DryRun is \c false, directly applies the changes.
694 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
695 std::set<LineState *, CompareLineStatePointers> Seen;
696
697 // Increasing count of \c StateNode items we have created. This is used to
698 // create a deterministic order independent of the container.
699 unsigned Count = 0;
700 QueueType Queue;
701
702 // Insert start element into queue.
703 StateNode *Node =
704 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
705 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
706 ++Count;
707
708 unsigned Penalty = 0;
709
710 // While not empty, take first element and follow edges.
711 while (!Queue.empty()) {
712 Penalty = Queue.top().first.first;
713 StateNode *Node = Queue.top().second;
714 if (!Node->State.NextToken) {
715 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
716 break;
717 }
718 Queue.pop();
719
720 // Cut off the analysis of certain solutions if the analysis gets too
721 // complex. See description of IgnoreStackForComparison.
Daniel Jasper75bf2032015-10-27 22:55:55 +0000722 if (Count > 50000)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000723 Node->State.IgnoreStackForComparison = true;
724
725 if (!Seen.insert(&Node->State).second)
726 // State already examined with lower penalty.
727 continue;
728
729 FormatDecision LastFormat = Node->State.NextToken->Decision;
730 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
731 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
732 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
733 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
734 }
735
736 if (Queue.empty()) {
737 // We were unable to find a solution, do nothing.
738 // FIXME: Add diagnostic?
739 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
740 return 0;
741 }
742
743 // Reconstruct the solution.
744 if (!DryRun)
745 reconstructPath(InitialState, Queue.top().second);
746
747 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
748 DEBUG(llvm::dbgs() << "---\n");
749
750 return Penalty;
751 }
752
753 /// \brief Add the following state to the analysis queue \c Queue.
754 ///
755 /// Assume the current state is \p PreviousNode and has been reached with a
756 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
757 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
758 bool NewLine, unsigned *Count, QueueType *Queue) {
759 if (NewLine && !Indenter->canBreak(PreviousNode->State))
760 return;
761 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
762 return;
763
764 StateNode *Node = new (Allocator.Allocate())
765 StateNode(PreviousNode->State, NewLine, PreviousNode);
766 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
767 return;
768
769 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
770
771 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
772 ++(*Count);
773 }
774
775 /// \brief Applies the best formatting by reconstructing the path in the
776 /// solution space that leads to \c Best.
777 void reconstructPath(LineState &State, StateNode *Best) {
778 std::deque<StateNode *> Path;
779 // We do not need a break before the initial token.
780 while (Best->Previous) {
781 Path.push_front(Best);
782 Best = Best->Previous;
783 }
784 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
785 I != E; ++I) {
786 unsigned Penalty = 0;
787 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
788 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
789
790 DEBUG({
791 printLineState((*I)->Previous->State);
792 if ((*I)->NewLine) {
793 llvm::dbgs() << "Penalty for placing "
794 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
795 << Penalty << "\n";
796 }
797 });
798 }
799 }
800
801 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
802};
803
Hans Wennborg7eb54642015-09-10 17:07:54 +0000804} // anonymous namespace
Daniel Jasper0df50932014-12-10 19:00:42 +0000805
806unsigned
807UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
808 bool DryRun, int AdditionalIndent,
809 bool FixBadIndentation) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000810 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +0000811
812 // Try to look up already computed penalty in DryRun-mode.
813 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
814 &Lines, AdditionalIndent);
815 auto CacheIt = PenaltyCache.find(CacheKey);
816 if (DryRun && CacheIt != PenaltyCache.end())
817 return CacheIt->second;
818
819 assert(!Lines.empty());
820 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000821 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
822 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000823 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000824 const AnnotatedLine *NextLine = nullptr;
Daniel Jasperf67c3242015-11-01 00:27:35 +0000825
826 // The minimum level of consecutive lines that have been formatted.
827 unsigned RangeMinLevel = UINT_MAX;
Daniel Jasperf67c3242015-11-01 00:27:35 +0000828
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000829 for (const AnnotatedLine *Line =
830 Joiner.getNextMergedLine(DryRun, IndentTracker);
831 Line; Line = NextLine) {
832 const AnnotatedLine &TheLine = *Line;
833 unsigned Indent = IndentTracker.getIndent();
Daniel Jasperf67c3242015-11-01 00:27:35 +0000834
835 // We continue formatting unchanged lines to adjust their indent, e.g. if a
836 // scope was added. However, we need to carefully stop doing this when we
837 // exit the scope of affected lines to prevent indenting a the entire
838 // remaining file if it currently missing a closing brace.
839 bool ContinueFormatting =
840 TheLine.Level > RangeMinLevel ||
Daniel Jasperf83834f2015-11-02 20:02:49 +0000841 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
Daniel Jasperf67c3242015-11-01 00:27:35 +0000842
843 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Daniel Jaspera1036e52015-10-28 01:08:22 +0000844 Indent != TheLine.First->OriginalColumn;
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000845 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000846 // We cannot format this line; if the reason is that the line had a
847 // parsing error, remember that.
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000848 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
849 Status->FormatComplete = false;
850 Status->Line =
851 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
852 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000853
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000854 if (ShouldFormat && TheLine.Type != LT_Invalid) {
855 if (!DryRun)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000856 formatFirstToken(TheLine, PreviousLine, Indent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000857
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000858 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
859 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
860 bool FitsIntoOneLine =
861 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
Martin Probst0cd74ee2016-06-13 16:39:50 +0000862 (TheLine.Type == LT_ImportStatement &&
863 (Style.Language != FormatStyle::LK_JavaScript ||
864 !Style.JavaScriptWrapImports));
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000865
866 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000867 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
868 .formatLine(TheLine, Indent, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000869 else if (FitsIntoOneLine)
870 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
871 .formatLine(TheLine, Indent, DryRun);
872 else
Manuel Klimekd3585db2015-05-11 08:21:35 +0000873 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
874 .formatLine(TheLine, Indent, DryRun);
Daniel Jasperf67c3242015-11-01 00:27:35 +0000875 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
Daniel Jasper0df50932014-12-10 19:00:42 +0000876 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000877 // If no token in the current line is affected, we still need to format
878 // affected children.
879 if (TheLine.ChildrenAffected)
Daniel Jasper35ca66d2016-02-29 12:26:20 +0000880 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
881 if (!Tok->Children.empty())
882 format(Tok->Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000883
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000884 // Adapt following lines on the current indent level to the same level
885 // unless the current \c AnnotatedLine is not at the beginning of a line.
886 bool StartsNewLine =
887 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
888 if (StartsNewLine)
889 IndentTracker.adjustToUnmodifiedLine(TheLine);
890 if (!DryRun) {
891 bool ReformatLeadingWhitespace =
892 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
893 TheLine.LeadingEmptyLinesAffected);
894 // Format the first token.
895 if (ReformatLeadingWhitespace)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000896 formatFirstToken(TheLine, PreviousLine,
897 TheLine.First->OriginalColumn);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000898 else
899 Whitespaces->addUntouchableToken(*TheLine.First,
900 TheLine.InPPDirective);
901
902 // Notify the WhitespaceManager about the unchanged whitespace.
903 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +0000904 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +0000905 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000906 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasperf67c3242015-11-01 00:27:35 +0000907 RangeMinLevel = UINT_MAX;
Daniel Jasper0df50932014-12-10 19:00:42 +0000908 }
Daniel Jasperd1c13732015-01-23 19:37:25 +0000909 if (!DryRun)
910 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000911 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +0000912 }
913 PenaltyCache[CacheKey] = Penalty;
914 return Penalty;
915}
916
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000917void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
Daniel Jasper0df50932014-12-10 19:00:42 +0000918 const AnnotatedLine *PreviousLine,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000919 unsigned Indent) {
920 FormatToken& RootToken = *Line.First;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000921 if (RootToken.is(tok::eof)) {
922 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000923 Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0,
Krasimir Georgiev9aceafd2017-03-08 09:02:39 +0000924 /*StartOfTokenColumn=*/0);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000925 return;
926 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000927 unsigned Newlines =
928 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
929 // Remove empty lines before "}" where applicable.
930 if (RootToken.is(tok::r_brace) &&
931 (!RootToken.Next ||
932 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
933 Newlines = std::min(Newlines, 1u);
934 if (Newlines == 0 && !RootToken.IsFirst)
935 Newlines = 1;
936 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
937 Newlines = 0;
938
939 // Remove empty lines after "{".
940 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
941 PreviousLine->Last->is(tok::l_brace) &&
942 PreviousLine->First->isNot(tok::kw_namespace) &&
943 !startsExternCBlock(*PreviousLine))
944 Newlines = 1;
945
946 // Insert extra new line before access specifiers.
947 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
948 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
949 ++Newlines;
950
951 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +0000952 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
953 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +0000954 Newlines = std::min(1u, Newlines);
955
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000956 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
957 Line.InPPDirective &&
958 !RootToken.HasUnescapedNewline);
Daniel Jasper0df50932014-12-10 19:00:42 +0000959}
960
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000961unsigned
962UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
963 const AnnotatedLine *NextLine) const {
964 // In preprocessor directives reserve two chars for trailing " \" if the
965 // next line continues the preprocessor directive.
966 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +0000967 InPPDirective &&
968 // If there is no next line, this is likely a child line and the parent
969 // continues the preprocessor directive.
970 (!NextLine ||
971 (NextLine->InPPDirective &&
972 // If there is an unescaped newline between this line and the next, the
973 // next line starts a new preprocessor directive.
974 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000975 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +0000976}
977
Daniel Jasper0df50932014-12-10 19:00:42 +0000978} // namespace format
979} // namespace clang