blob: b01d989f88fd21ef0f60cfd1b0e02e376a3025fb [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"
13
14#define DEBUG_TYPE "format-formatter"
15
16namespace clang {
17namespace format {
18
19namespace {
20
21bool startsExternCBlock(const AnnotatedLine &Line) {
22 const FormatToken *Next = Line.First->getNextNonComment();
23 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
24 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
25 NextNext && NextNext->is(tok::l_brace);
26}
27
Manuel Klimek3d3ea842015-05-12 09:23:57 +000028/// \brief Tracks the indent level of \c AnnotatedLines across levels.
29///
30/// \c nextLine must be called for each \c AnnotatedLine, after which \c
31/// getIndent() will return the indent for the last line \c nextLine was called
32/// with.
33/// If the line is not formatted (and thus the indent does not change), calling
34/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
35/// subsequent lines on the same level to be indented at the same level as the
36/// given line.
37class LevelIndentTracker {
38public:
39 LevelIndentTracker(const FormatStyle &Style,
40 const AdditionalKeywords &Keywords, unsigned StartLevel,
41 int AdditionalIndent)
42 : Style(Style), Keywords(Keywords) {
43 for (unsigned i = 0; i != StartLevel; ++i)
44 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
45 }
46
47 /// \brief Returns the indent for the current line.
48 unsigned getIndent() const { return Indent; }
49
50 /// \brief Update the indent state given that \p Line is going to be formatted
51 /// next.
52 void nextLine(const AnnotatedLine &Line) {
53 Offset = getIndentOffset(*Line.First);
54 if (Line.InPPDirective) {
55 Indent = Line.Level * Style.IndentWidth;
56 } else {
57 while (IndentForLevel.size() <= Line.Level)
58 IndentForLevel.push_back(-1);
59 IndentForLevel.resize(Line.Level + 1);
60 Indent = getIndent(IndentForLevel, Line.Level);
61 }
62 if (static_cast<int>(Indent) + Offset >= 0)
63 Indent += Offset;
64 }
65
66 /// \brief Update the level indent to adapt to the given \p Line.
67 ///
68 /// When a line is not formatted, we move the subsequent lines on the same
69 /// level to the same indent.
70 /// Note that \c nextLine must have been called before this method.
71 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
72 unsigned LevelIndent = Line.First->OriginalColumn;
73 if (static_cast<int>(LevelIndent) - Offset >= 0)
74 LevelIndent -= Offset;
75 if ((Line.First->isNot(tok::comment) || IndentForLevel[Line.Level] == -1) &&
76 !Line.InPPDirective)
77 IndentForLevel[Line.Level] = LevelIndent;
78 }
79
80private:
81 /// \brief Get the offset of the line relatively to the level.
82 ///
83 /// For example, 'public:' labels in classes are offset by 1 or 2
84 /// characters to the left from their level.
85 int getIndentOffset(const FormatToken &RootToken) {
86 if (Style.Language == FormatStyle::LK_Java ||
87 Style.Language == FormatStyle::LK_JavaScript)
88 return 0;
89 if (RootToken.isAccessSpecifier(false) ||
90 RootToken.isObjCAccessSpecifier() ||
91 (RootToken.is(Keywords.kw_signals) && RootToken.Next &&
92 RootToken.Next->is(tok::colon)))
93 return Style.AccessModifierOffset;
94 return 0;
95 }
96
97 /// \brief Get the indent of \p Level from \p IndentForLevel.
98 ///
99 /// \p IndentForLevel must contain the indent for the level \c l
100 /// at \p IndentForLevel[l], or a value < 0 if the indent for
101 /// that level is unknown.
102 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
103 if (IndentForLevel[Level] != -1)
104 return IndentForLevel[Level];
105 if (Level == 0)
106 return 0;
107 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
108 }
109
110 const FormatStyle &Style;
111 const AdditionalKeywords &Keywords;
112
113 /// \brief The indent in characters for each level.
114 std::vector<int> IndentForLevel;
115
116 /// \brief Offset of the current line relative to the indent level.
117 ///
118 /// For example, the 'public' keywords is often indented with a negative
119 /// offset.
120 int Offset = 0;
121
122 /// \brief The current line's indent.
123 unsigned Indent = 0;
124};
125
Daniel Jasper0df50932014-12-10 19:00:42 +0000126class LineJoiner {
127public:
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000128 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
129 const SmallVectorImpl<AnnotatedLine *> &Lines)
130 : Style(Style), Keywords(Keywords), End(Lines.end()),
131 Next(Lines.begin()) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000132
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000133 /// \brief Returns the next line, merging multiple lines into one if possible.
134 const AnnotatedLine *getNextMergedLine(bool DryRun,
135 LevelIndentTracker &IndentTracker) {
136 if (Next == End)
137 return nullptr;
138 const AnnotatedLine *Current = *Next;
139 IndentTracker.nextLine(*Current);
140 unsigned MergedLines =
141 tryFitMultipleLinesInOne(IndentTracker.getIndent(), Next, End);
142 if (MergedLines > 0 && Style.ColumnLimit == 0)
143 // Disallow line merging if there is a break at the start of one of the
144 // input lines.
145 for (unsigned i = 0; i < MergedLines; ++i)
146 if (Next[i + 1]->First->NewlinesBefore > 0)
147 MergedLines = 0;
148 if (!DryRun)
149 for (unsigned i = 0; i < MergedLines; ++i)
150 join(*Next[i], *Next[i + 1]);
151 Next = Next + MergedLines + 1;
152 return Current;
153 }
154
155private:
Daniel Jasper0df50932014-12-10 19:00:42 +0000156 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
157 unsigned
158 tryFitMultipleLinesInOne(unsigned Indent,
159 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
160 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000161 // Can't join the last line with anything.
162 if (I + 1 == E)
163 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000164 // We can never merge stuff if there are trailing line comments.
165 const AnnotatedLine *TheLine = *I;
166 if (TheLine->Last->is(TT_LineComment))
167 return 0;
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000168 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
169 return 0;
170 if (TheLine->InPPDirective &&
171 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
172 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000173
174 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
175 return 0;
176
177 unsigned Limit =
178 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
179 // If we already exceed the column limit, we set 'Limit' to 0. The different
180 // tryMerge..() functions can then decide whether to still do merging.
181 Limit = TheLine->Last->TotalLength > Limit
182 ? 0
183 : Limit - TheLine->Last->TotalLength;
184
Daniel Jasper0df50932014-12-10 19:00:42 +0000185 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
186 // If necessary, change to something smarter.
187 bool MergeShortFunctions =
188 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
189 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
190 I[1]->First->is(tok::r_brace)) ||
191 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
192 TheLine->Level != 0);
193
194 if (TheLine->Last->is(TT_FunctionLBrace) &&
195 TheLine->First != TheLine->Last) {
196 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
197 }
198 if (TheLine->Last->is(tok::l_brace)) {
199 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
200 ? tryMergeSimpleBlock(I, E, Limit)
201 : 0;
202 }
203 if (I[1]->First->is(TT_FunctionLBrace) &&
204 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
205 if (I[1]->Last->is(TT_LineComment))
206 return 0;
207
208 // Check for Limit <= 2 to account for the " {".
209 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
210 return 0;
211 Limit -= 2;
212
213 unsigned MergedLines = 0;
214 if (MergeShortFunctions) {
215 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
216 // If we managed to merge the block, count the function header, which is
217 // on a separate line.
218 if (MergedLines > 0)
219 ++MergedLines;
220 }
221 return MergedLines;
222 }
223 if (TheLine->First->is(tok::kw_if)) {
224 return Style.AllowShortIfStatementsOnASingleLine
225 ? tryMergeSimpleControlStatement(I, E, Limit)
226 : 0;
227 }
228 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
229 return Style.AllowShortLoopsOnASingleLine
230 ? tryMergeSimpleControlStatement(I, E, Limit)
231 : 0;
232 }
233 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
234 return Style.AllowShortCaseLabelsOnASingleLine
235 ? tryMergeShortCaseLabels(I, E, Limit)
236 : 0;
237 }
238 if (TheLine->InPPDirective &&
239 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
240 return tryMergeSimplePPDirective(I, E, Limit);
241 }
242 return 0;
243 }
244
Daniel Jasper0df50932014-12-10 19:00:42 +0000245 unsigned
246 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
247 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
248 unsigned Limit) {
249 if (Limit == 0)
250 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000251 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
252 return 0;
253 if (1 + I[1]->Last->TotalLength > Limit)
254 return 0;
255 return 1;
256 }
257
258 unsigned tryMergeSimpleControlStatement(
259 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
260 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
261 if (Limit == 0)
262 return 0;
263 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
264 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
265 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
266 return 0;
267 if (I[1]->InPPDirective != (*I)->InPPDirective ||
268 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
269 return 0;
270 Limit = limitConsideringMacros(I + 1, E, Limit);
271 AnnotatedLine &Line = **I;
272 if (Line.Last->isNot(tok::r_paren))
273 return 0;
274 if (1 + I[1]->Last->TotalLength > Limit)
275 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000276 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
277 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000278 return 0;
279 // Only inline simple if's (no nested if or else).
280 if (I + 2 != E && Line.First->is(tok::kw_if) &&
281 I[2]->First->is(tok::kw_else))
282 return 0;
283 return 1;
284 }
285
Manuel Klimekd3585db2015-05-11 08:21:35 +0000286 unsigned
287 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
288 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
289 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000290 if (Limit == 0 || I + 1 == E ||
291 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
292 return 0;
293 unsigned NumStmts = 0;
294 unsigned Length = 0;
295 bool InPPDirective = I[0]->InPPDirective;
296 for (; NumStmts < 3; ++NumStmts) {
297 if (I + 1 + NumStmts == E)
298 break;
299 const AnnotatedLine *Line = I[1 + NumStmts];
300 if (Line->InPPDirective != InPPDirective)
301 break;
302 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
303 break;
304 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
305 tok::kw_while, tok::comment))
306 return 0;
307 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
308 }
309 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
310 return 0;
311 return NumStmts;
312 }
313
314 unsigned
315 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
316 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
317 unsigned Limit) {
318 AnnotatedLine &Line = **I;
319
320 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000321 // FIXME: If an option to allow short exception handling clauses on a single
322 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000323 if (Style.Language != FormatStyle::LK_Java &&
324 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
325 return 0;
326
327 // Check that the current line allows merging. This depends on whether we
328 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000329 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
330 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000331 return 0;
332 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000333 tok::kw___try, tok::kw_catch, tok::kw___finally,
334 tok::kw_for, tok::r_brace) ||
335 Line.First->is(Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000336 if (!Style.AllowShortBlocksOnASingleLine)
337 return 0;
338 if (!Style.AllowShortIfStatementsOnASingleLine &&
339 Line.First->is(tok::kw_if))
340 return 0;
341 if (!Style.AllowShortLoopsOnASingleLine &&
342 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
343 return 0;
344 // FIXME: Consider an option to allow short exception handling clauses on
345 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000346 // FIXME: This isn't covered by tests.
347 // FIXME: For catch, __except, __finally the first token on the line
348 // is '}', so this isn't correct here.
349 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
350 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000351 return 0;
352 }
353
354 FormatToken *Tok = I[1]->First;
355 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
356 (Tok->getNextNonComment() == nullptr ||
357 Tok->getNextNonComment()->is(tok::semi))) {
358 // We merge empty blocks even if the line exceeds the column limit.
359 Tok->SpacesRequiredBefore = 0;
360 Tok->CanBreakBefore = true;
361 return 1;
362 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
363 !startsExternCBlock(Line)) {
364 // We don't merge short records.
Daniel Jasper29647492015-05-05 08:12:50 +0000365 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
366 Keywords.kw_interface))
Daniel Jasper0df50932014-12-10 19:00:42 +0000367 return 0;
368
369 // Check that we still have three lines and they fit into the limit.
370 if (I + 2 == E || I[2]->Type == LT_Invalid)
371 return 0;
372 Limit = limitConsideringMacros(I + 2, E, Limit);
373
374 if (!nextTwoLinesFitInto(I, Limit))
375 return 0;
376
377 // Second, check that the next line does not contain any braces - if it
378 // does, readability declines when putting it into a single line.
379 if (I[1]->Last->is(TT_LineComment))
380 return 0;
381 do {
382 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
383 return 0;
384 Tok = Tok->Next;
385 } while (Tok);
386
387 // Last, check that the third line starts with a closing brace.
388 Tok = I[2]->First;
389 if (Tok->isNot(tok::r_brace))
390 return 0;
391
Daniel Jaspere9f53572015-04-30 09:24:17 +0000392 // Don't merge "if (a) { .. } else {".
393 if (Tok->Next && Tok->Next->is(tok::kw_else))
394 return 0;
395
Daniel Jasper0df50932014-12-10 19:00:42 +0000396 return 2;
397 }
398 return 0;
399 }
400
401 /// Returns the modified column limit for \p I if it is inside a macro and
402 /// needs a trailing '\'.
403 unsigned
404 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
405 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
406 unsigned Limit) {
407 if (I[0]->InPPDirective && I + 1 != E &&
408 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
409 return Limit < 2 ? 0 : Limit - 2;
410 }
411 return Limit;
412 }
413
414 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
415 unsigned Limit) {
416 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
417 return false;
418 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
419 }
420
421 bool containsMustBreak(const AnnotatedLine *Line) {
422 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
423 if (Tok->MustBreakBefore)
424 return true;
425 }
426 return false;
427 }
428
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000429 void join(AnnotatedLine &A, const AnnotatedLine &B) {
430 assert(!A.Last->Next);
431 assert(!B.First->Previous);
432 if (B.Affected)
433 A.Affected = true;
434 A.Last->Next = B.First;
435 B.First->Previous = A.Last;
436 B.First->CanBreakBefore = true;
437 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
438 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
439 Tok->TotalLength += LengthA;
440 A.Last = Tok;
441 }
442 }
443
Daniel Jasper0df50932014-12-10 19:00:42 +0000444 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000445 const AdditionalKeywords &Keywords;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000446 const SmallVectorImpl<AnnotatedLine*>::const_iterator End;
447
448 SmallVectorImpl<AnnotatedLine*>::const_iterator Next;
Daniel Jasper0df50932014-12-10 19:00:42 +0000449};
450
Daniel Jasperd1c13732015-01-23 19:37:25 +0000451static void markFinalized(FormatToken *Tok) {
452 for (; Tok; Tok = Tok->Next) {
453 Tok->Finalized = true;
454 for (AnnotatedLine *Child : Tok->Children)
455 markFinalized(Child->First);
456 }
457}
458
Manuel Klimekd3585db2015-05-11 08:21:35 +0000459#ifndef NDEBUG
460static void printLineState(const LineState &State) {
461 llvm::dbgs() << "State: ";
462 for (const ParenState &P : State.Stack) {
463 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
464 << " ";
465 }
466 llvm::dbgs() << State.NextToken->TokenText << "\n";
467}
468#endif
469
470/// \brief Base class for classes that format one \c AnnotatedLine.
471class LineFormatter {
472public:
473 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
474 const FormatStyle &Style,
475 UnwrappedLineFormatter *BlockFormatter)
476 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
477 BlockFormatter(BlockFormatter) {}
478 virtual ~LineFormatter() {}
479
480 /// \brief Formats an \c AnnotatedLine and returns the penalty.
481 ///
482 /// If \p DryRun is \c false, directly applies the changes.
483 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
484 bool DryRun) = 0;
485
486protected:
487 /// \brief If the \p State's next token is an r_brace closing a nested block,
488 /// format the nested block before it.
489 ///
490 /// Returns \c true if all children could be placed successfully and adapts
491 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
492 /// creates changes using \c Whitespaces.
493 ///
494 /// The crucial idea here is that children always get formatted upon
495 /// encountering the closing brace right after the nested block. Now, if we
496 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
497 /// \c false), the entire block has to be kept on the same line (which is only
498 /// possible if it fits on the line, only contains a single statement, etc.
499 ///
500 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
501 /// break after the "{", format all lines with correct indentation and the put
502 /// the closing "}" on yet another new line.
503 ///
504 /// This enables us to keep the simple structure of the
505 /// \c UnwrappedLineFormatter, where we only have two options for each token:
506 /// break or don't break.
507 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
508 unsigned &Penalty) {
509 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
510 FormatToken &Previous = *State.NextToken->Previous;
511 if (!LBrace || LBrace->isNot(tok::l_brace) ||
512 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
513 // The previous token does not open a block. Nothing to do. We don't
514 // assert so that we can simply call this function for all tokens.
515 return true;
516
517 if (NewLine) {
518 int AdditionalIndent = State.Stack.back().Indent -
519 Previous.Children[0]->Level * Style.IndentWidth;
520
521 Penalty +=
522 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
523 /*FixBadIndentation=*/true);
524 return true;
525 }
526
527 if (Previous.Children[0]->First->MustBreakBefore)
528 return false;
529
530 // Cannot merge multiple statements into a single line.
531 if (Previous.Children.size() > 1)
532 return false;
533
534 // Cannot merge into one line if this line ends on a comment.
535 if (Previous.is(tok::comment))
536 return false;
537
538 // We can't put the closing "}" on a line with a trailing comment.
539 if (Previous.Children[0]->Last->isTrailingComment())
540 return false;
541
542 // If the child line exceeds the column limit, we wouldn't want to merge it.
543 // We add +2 for the trailing " }".
544 if (Style.ColumnLimit > 0 &&
545 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
546 Style.ColumnLimit)
547 return false;
548
549 if (!DryRun) {
550 Whitespaces->replaceWhitespace(
551 *Previous.Children[0]->First,
552 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
553 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
554 }
555 Penalty += formatLine(*Previous.Children[0], State.Column + 1, DryRun);
556
557 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
558 return true;
559 }
560
561 ContinuationIndenter *Indenter;
562
563private:
564 WhitespaceManager *Whitespaces;
565 const FormatStyle &Style;
566 UnwrappedLineFormatter *BlockFormatter;
567};
568
569/// \brief Formatter that keeps the existing line breaks.
570class NoColumnLimitLineFormatter : public LineFormatter {
571public:
572 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
573 WhitespaceManager *Whitespaces,
574 const FormatStyle &Style,
575 UnwrappedLineFormatter *BlockFormatter)
576 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
577
578 /// \brief Formats the line, simply keeping all of the input's line breaking
579 /// decisions.
580 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
581 bool DryRun) override {
582 assert(!DryRun);
583 LineState State =
584 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
585 while (State.NextToken) {
586 bool Newline =
587 Indenter->mustBreak(State) ||
588 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
589 unsigned Penalty = 0;
590 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
591 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
592 }
593 return 0;
594 }
595};
596
597/// \brief Formatter that puts all tokens into a single line without breaks.
598class NoLineBreakFormatter : public LineFormatter {
599public:
600 NoLineBreakFormatter(ContinuationIndenter *Indenter,
601 WhitespaceManager *Whitespaces, const FormatStyle &Style,
602 UnwrappedLineFormatter *BlockFormatter)
603 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
604
605 /// \brief Puts all tokens into a single line.
606 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
607 bool DryRun) {
608 unsigned Penalty = 0;
609 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
610 while (State.NextToken) {
611 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
612 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
613 }
614 return Penalty;
615 }
616};
617
618/// \brief Finds the best way to break lines.
619class OptimizingLineFormatter : public LineFormatter {
620public:
621 OptimizingLineFormatter(ContinuationIndenter *Indenter,
622 WhitespaceManager *Whitespaces,
623 const FormatStyle &Style,
624 UnwrappedLineFormatter *BlockFormatter)
625 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
626
627 /// \brief Formats the line by finding the best line breaks with line lengths
628 /// below the column limit.
629 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
630 bool DryRun) {
631 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
632
633 // If the ObjC method declaration does not fit on a line, we should format
634 // it with one arg per line.
635 if (State.Line->Type == LT_ObjCMethodDecl)
636 State.Stack.back().BreakBeforeParameter = true;
637
638 // Find best solution in solution space.
639 return analyzeSolutionSpace(State, DryRun);
640 }
641
642private:
643 struct CompareLineStatePointers {
644 bool operator()(LineState *obj1, LineState *obj2) const {
645 return *obj1 < *obj2;
646 }
647 };
648
649 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
650 ///
651 /// In case of equal penalties, we want to prefer states that were inserted
652 /// first. During state generation we make sure that we insert states first
653 /// that break the line as late as possible.
654 typedef std::pair<unsigned, unsigned> OrderedPenalty;
655
656 /// \brief An edge in the solution space from \c Previous->State to \c State,
657 /// inserting a newline dependent on the \c NewLine.
658 struct StateNode {
659 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
660 : State(State), NewLine(NewLine), Previous(Previous) {}
661 LineState State;
662 bool NewLine;
663 StateNode *Previous;
664 };
665
666 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
667 /// \c State has the given \c OrderedPenalty.
668 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
669
670 /// \brief The BFS queue type.
671 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
672 std::greater<QueueItem>> QueueType;
673
674 /// \brief Analyze the entire solution space starting from \p InitialState.
675 ///
676 /// This implements a variant of Dijkstra's algorithm on the graph that spans
677 /// the solution space (\c LineStates are the nodes). The algorithm tries to
678 /// find the shortest path (the one with lowest penalty) from \p InitialState
679 /// to a state where all tokens are placed. Returns the penalty.
680 ///
681 /// If \p DryRun is \c false, directly applies the changes.
682 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
683 std::set<LineState *, CompareLineStatePointers> Seen;
684
685 // Increasing count of \c StateNode items we have created. This is used to
686 // create a deterministic order independent of the container.
687 unsigned Count = 0;
688 QueueType Queue;
689
690 // Insert start element into queue.
691 StateNode *Node =
692 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
693 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
694 ++Count;
695
696 unsigned Penalty = 0;
697
698 // While not empty, take first element and follow edges.
699 while (!Queue.empty()) {
700 Penalty = Queue.top().first.first;
701 StateNode *Node = Queue.top().second;
702 if (!Node->State.NextToken) {
703 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
704 break;
705 }
706 Queue.pop();
707
708 // Cut off the analysis of certain solutions if the analysis gets too
709 // complex. See description of IgnoreStackForComparison.
710 if (Count > 10000)
711 Node->State.IgnoreStackForComparison = true;
712
713 if (!Seen.insert(&Node->State).second)
714 // State already examined with lower penalty.
715 continue;
716
717 FormatDecision LastFormat = Node->State.NextToken->Decision;
718 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
719 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
720 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
721 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
722 }
723
724 if (Queue.empty()) {
725 // We were unable to find a solution, do nothing.
726 // FIXME: Add diagnostic?
727 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
728 return 0;
729 }
730
731 // Reconstruct the solution.
732 if (!DryRun)
733 reconstructPath(InitialState, Queue.top().second);
734
735 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
736 DEBUG(llvm::dbgs() << "---\n");
737
738 return Penalty;
739 }
740
741 /// \brief Add the following state to the analysis queue \c Queue.
742 ///
743 /// Assume the current state is \p PreviousNode and has been reached with a
744 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
745 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
746 bool NewLine, unsigned *Count, QueueType *Queue) {
747 if (NewLine && !Indenter->canBreak(PreviousNode->State))
748 return;
749 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
750 return;
751
752 StateNode *Node = new (Allocator.Allocate())
753 StateNode(PreviousNode->State, NewLine, PreviousNode);
754 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
755 return;
756
757 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
758
759 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
760 ++(*Count);
761 }
762
763 /// \brief Applies the best formatting by reconstructing the path in the
764 /// solution space that leads to \c Best.
765 void reconstructPath(LineState &State, StateNode *Best) {
766 std::deque<StateNode *> Path;
767 // We do not need a break before the initial token.
768 while (Best->Previous) {
769 Path.push_front(Best);
770 Best = Best->Previous;
771 }
772 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
773 I != E; ++I) {
774 unsigned Penalty = 0;
775 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
776 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
777
778 DEBUG({
779 printLineState((*I)->Previous->State);
780 if ((*I)->NewLine) {
781 llvm::dbgs() << "Penalty for placing "
782 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
783 << Penalty << "\n";
784 }
785 });
786 }
787 }
788
789 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
790};
791
Daniel Jasper0df50932014-12-10 19:00:42 +0000792} // namespace
793
794unsigned
795UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
796 bool DryRun, int AdditionalIndent,
797 bool FixBadIndentation) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000798 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +0000799
800 // Try to look up already computed penalty in DryRun-mode.
801 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
802 &Lines, AdditionalIndent);
803 auto CacheIt = PenaltyCache.find(CacheKey);
804 if (DryRun && CacheIt != PenaltyCache.end())
805 return CacheIt->second;
806
807 assert(!Lines.empty());
808 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000809 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
810 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000811 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000812 const AnnotatedLine *NextLine = nullptr;
813 for (const AnnotatedLine *Line =
814 Joiner.getNextMergedLine(DryRun, IndentTracker);
815 Line; Line = NextLine) {
816 const AnnotatedLine &TheLine = *Line;
817 unsigned Indent = IndentTracker.getIndent();
Daniel Jasper0df50932014-12-10 19:00:42 +0000818 bool FixIndentation =
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000819 FixBadIndentation && (Indent != TheLine.First->OriginalColumn);
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000820 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000821 // We cannot format this line; if the reason is that the line had a
822 // parsing error, remember that.
823 if (ShouldFormat && TheLine.Type == LT_Invalid && IncompleteFormat)
824 *IncompleteFormat = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000825
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000826 if (ShouldFormat && TheLine.Type != LT_Invalid) {
827 if (!DryRun)
828 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
829 TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +0000830
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000831 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
832 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
833 bool FitsIntoOneLine =
834 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
835 TheLine.Type == LT_ImportStatement;
836
837 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000838 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
839 .formatLine(TheLine, Indent, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000840 else if (FitsIntoOneLine)
841 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
842 .formatLine(TheLine, Indent, DryRun);
843 else
Manuel Klimekd3585db2015-05-11 08:21:35 +0000844 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
845 .formatLine(TheLine, Indent, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000846 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000847 // If no token in the current line is affected, we still need to format
848 // affected children.
849 if (TheLine.ChildrenAffected)
850 format(TheLine.Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000851
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000852 // Adapt following lines on the current indent level to the same level
853 // unless the current \c AnnotatedLine is not at the beginning of a line.
854 bool StartsNewLine =
855 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
856 if (StartsNewLine)
857 IndentTracker.adjustToUnmodifiedLine(TheLine);
858 if (!DryRun) {
859 bool ReformatLeadingWhitespace =
860 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
861 TheLine.LeadingEmptyLinesAffected);
862 // Format the first token.
863 if (ReformatLeadingWhitespace)
864 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
865 TheLine.First->OriginalColumn,
866 TheLine.InPPDirective);
867 else
868 Whitespaces->addUntouchableToken(*TheLine.First,
869 TheLine.InPPDirective);
870
871 // Notify the WhitespaceManager about the unchanged whitespace.
872 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +0000873 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +0000874 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000875 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasper0df50932014-12-10 19:00:42 +0000876 }
Daniel Jasperd1c13732015-01-23 19:37:25 +0000877 if (!DryRun)
878 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000879 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +0000880 }
881 PenaltyCache[CacheKey] = Penalty;
882 return Penalty;
883}
884
Daniel Jasper0df50932014-12-10 19:00:42 +0000885void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
886 const AnnotatedLine *PreviousLine,
887 unsigned IndentLevel,
888 unsigned Indent,
889 bool InPPDirective) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000890 if (RootToken.is(tok::eof)) {
891 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
892 Whitespaces->replaceWhitespace(RootToken, Newlines, /*IndentLevel=*/0,
893 /*Spaces=*/0, /*TargetColumn=*/0);
894 return;
895 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000896 unsigned Newlines =
897 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
898 // Remove empty lines before "}" where applicable.
899 if (RootToken.is(tok::r_brace) &&
900 (!RootToken.Next ||
901 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
902 Newlines = std::min(Newlines, 1u);
903 if (Newlines == 0 && !RootToken.IsFirst)
904 Newlines = 1;
905 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
906 Newlines = 0;
907
908 // Remove empty lines after "{".
909 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
910 PreviousLine->Last->is(tok::l_brace) &&
911 PreviousLine->First->isNot(tok::kw_namespace) &&
912 !startsExternCBlock(*PreviousLine))
913 Newlines = 1;
914
915 // Insert extra new line before access specifiers.
916 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
917 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
918 ++Newlines;
919
920 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +0000921 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
922 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +0000923 Newlines = std::min(1u, Newlines);
924
925 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
926 Indent, InPPDirective &&
927 !RootToken.HasUnescapedNewline);
928}
929
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000930unsigned
931UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
932 const AnnotatedLine *NextLine) const {
933 // In preprocessor directives reserve two chars for trailing " \" if the
934 // next line continues the preprocessor directive.
935 bool ContinuesPPDirective =
936 InPPDirective && NextLine && NextLine->InPPDirective &&
937 // If there is an unescaped newline between this line and the next, the
938 // next line starts a new preprocessor directive.
939 !NextLine->First->HasUnescapedNewline;
940 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +0000941}
942
Daniel Jasper0df50932014-12-10 19:00:42 +0000943} // namespace format
944} // namespace clang