blob: 191b78d061af2b893c08693b45a7dbda532fd0b7 [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)
Daniel Jasper5fc133e2015-05-12 10:16:02 +000042 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000043 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);
Manuel Klimekf0c95b32015-06-11 10:14:13 +000054 // Update the indent level cache size so that we can rely on it
55 // having the right size in adjustToUnmodifiedline.
56 while (IndentForLevel.size() <= Line.Level)
57 IndentForLevel.push_back(-1);
Manuel Klimek3d3ea842015-05-12 09:23:57 +000058 if (Line.InPPDirective) {
Daniel Jasper5fc133e2015-05-12 10:16:02 +000059 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
Manuel Klimek3d3ea842015-05-12 09:23:57 +000060 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000061 IndentForLevel.resize(Line.Level + 1);
62 Indent = getIndent(IndentForLevel, Line.Level);
63 }
64 if (static_cast<int>(Indent) + Offset >= 0)
65 Indent += Offset;
66 }
67
68 /// \brief Update the level indent to adapt to the given \p Line.
69 ///
70 /// When a line is not formatted, we move the subsequent lines on the same
71 /// level to the same indent.
72 /// Note that \c nextLine must have been called before this method.
73 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
74 unsigned LevelIndent = Line.First->OriginalColumn;
75 if (static_cast<int>(LevelIndent) - Offset >= 0)
76 LevelIndent -= Offset;
77 if ((Line.First->isNot(tok::comment) || IndentForLevel[Line.Level] == -1) &&
78 !Line.InPPDirective)
79 IndentForLevel[Line.Level] = LevelIndent;
80 }
81
82private:
83 /// \brief Get the offset of the line relatively to the level.
84 ///
85 /// For example, 'public:' labels in classes are offset by 1 or 2
86 /// characters to the left from their level.
87 int getIndentOffset(const FormatToken &RootToken) {
88 if (Style.Language == FormatStyle::LK_Java ||
89 Style.Language == FormatStyle::LK_JavaScript)
90 return 0;
91 if (RootToken.isAccessSpecifier(false) ||
92 RootToken.isObjCAccessSpecifier() ||
93 (RootToken.is(Keywords.kw_signals) && RootToken.Next &&
94 RootToken.Next->is(tok::colon)))
95 return Style.AccessModifierOffset;
96 return 0;
97 }
98
99 /// \brief Get the indent of \p Level from \p IndentForLevel.
100 ///
101 /// \p IndentForLevel must contain the indent for the level \c l
102 /// at \p IndentForLevel[l], or a value < 0 if the indent for
103 /// that level is unknown.
104 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
105 if (IndentForLevel[Level] != -1)
106 return IndentForLevel[Level];
107 if (Level == 0)
108 return 0;
109 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
110 }
111
112 const FormatStyle &Style;
113 const AdditionalKeywords &Keywords;
Daniel Jasper56807c12015-05-12 11:14:06 +0000114 const unsigned AdditionalIndent;
Daniel Jasper5fc133e2015-05-12 10:16:02 +0000115
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000116 /// \brief The indent in characters for each level.
117 std::vector<int> IndentForLevel;
118
119 /// \brief Offset of the current line relative to the indent level.
120 ///
121 /// For example, the 'public' keywords is often indented with a negative
122 /// offset.
123 int Offset = 0;
124
125 /// \brief The current line's indent.
126 unsigned Indent = 0;
127};
128
Daniel Jasper0df50932014-12-10 19:00:42 +0000129class LineJoiner {
130public:
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000131 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
132 const SmallVectorImpl<AnnotatedLine *> &Lines)
133 : Style(Style), Keywords(Keywords), End(Lines.end()),
134 Next(Lines.begin()) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000135
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000136 /// \brief Returns the next line, merging multiple lines into one if possible.
137 const AnnotatedLine *getNextMergedLine(bool DryRun,
138 LevelIndentTracker &IndentTracker) {
139 if (Next == End)
140 return nullptr;
141 const AnnotatedLine *Current = *Next;
142 IndentTracker.nextLine(*Current);
143 unsigned MergedLines =
144 tryFitMultipleLinesInOne(IndentTracker.getIndent(), Next, End);
145 if (MergedLines > 0 && Style.ColumnLimit == 0)
146 // Disallow line merging if there is a break at the start of one of the
147 // input lines.
148 for (unsigned i = 0; i < MergedLines; ++i)
149 if (Next[i + 1]->First->NewlinesBefore > 0)
150 MergedLines = 0;
151 if (!DryRun)
152 for (unsigned i = 0; i < MergedLines; ++i)
153 join(*Next[i], *Next[i + 1]);
154 Next = Next + MergedLines + 1;
155 return Current;
156 }
157
158private:
Daniel Jasper0df50932014-12-10 19:00:42 +0000159 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
160 unsigned
161 tryFitMultipleLinesInOne(unsigned Indent,
162 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
163 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000164 // Can't join the last line with anything.
165 if (I + 1 == E)
166 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000167 // We can never merge stuff if there are trailing line comments.
168 const AnnotatedLine *TheLine = *I;
169 if (TheLine->Last->is(TT_LineComment))
170 return 0;
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000171 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
172 return 0;
173 if (TheLine->InPPDirective &&
174 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
175 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000176
177 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
178 return 0;
179
180 unsigned Limit =
181 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
182 // If we already exceed the column limit, we set 'Limit' to 0. The different
183 // tryMerge..() functions can then decide whether to still do merging.
184 Limit = TheLine->Last->TotalLength > Limit
185 ? 0
186 : Limit - TheLine->Last->TotalLength;
187
Daniel Jasper0df50932014-12-10 19:00:42 +0000188 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
189 // If necessary, change to something smarter.
190 bool MergeShortFunctions =
191 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper20580fd2015-06-11 13:31:45 +0000192 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000193 I[1]->First->is(tok::r_brace)) ||
194 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
195 TheLine->Level != 0);
196
197 if (TheLine->Last->is(TT_FunctionLBrace) &&
198 TheLine->First != TheLine->Last) {
199 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
200 }
201 if (TheLine->Last->is(tok::l_brace)) {
202 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
203 ? tryMergeSimpleBlock(I, E, Limit)
204 : 0;
205 }
206 if (I[1]->First->is(TT_FunctionLBrace) &&
207 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
208 if (I[1]->Last->is(TT_LineComment))
209 return 0;
210
211 // Check for Limit <= 2 to account for the " {".
212 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
213 return 0;
214 Limit -= 2;
215
216 unsigned MergedLines = 0;
217 if (MergeShortFunctions) {
218 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
219 // If we managed to merge the block, count the function header, which is
220 // on a separate line.
221 if (MergedLines > 0)
222 ++MergedLines;
223 }
224 return MergedLines;
225 }
226 if (TheLine->First->is(tok::kw_if)) {
227 return Style.AllowShortIfStatementsOnASingleLine
228 ? tryMergeSimpleControlStatement(I, E, Limit)
229 : 0;
230 }
231 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
232 return Style.AllowShortLoopsOnASingleLine
233 ? tryMergeSimpleControlStatement(I, E, Limit)
234 : 0;
235 }
236 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
237 return Style.AllowShortCaseLabelsOnASingleLine
238 ? tryMergeShortCaseLabels(I, E, Limit)
239 : 0;
240 }
241 if (TheLine->InPPDirective &&
242 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
243 return tryMergeSimplePPDirective(I, E, Limit);
244 }
245 return 0;
246 }
247
Daniel Jasper0df50932014-12-10 19:00:42 +0000248 unsigned
249 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
250 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
251 unsigned Limit) {
252 if (Limit == 0)
253 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000254 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
255 return 0;
256 if (1 + I[1]->Last->TotalLength > Limit)
257 return 0;
258 return 1;
259 }
260
261 unsigned tryMergeSimpleControlStatement(
262 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
263 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
264 if (Limit == 0)
265 return 0;
266 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
267 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
268 (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).
283 if (I + 2 != E && Line.First->is(tok::kw_if) &&
284 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,
308 tok::kw_while, tok::comment))
309 return 0;
310 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
311 }
312 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
313 return 0;
314 return NumStmts;
315 }
316
317 unsigned
318 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
319 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
320 unsigned Limit) {
321 AnnotatedLine &Line = **I;
322
323 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000324 // FIXME: If an option to allow short exception handling clauses on a single
325 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000326 if (Style.Language != FormatStyle::LK_Java &&
327 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
328 return 0;
329
330 // Check that the current line allows merging. This depends on whether we
331 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000332 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
333 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000334 return 0;
335 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000336 tok::kw___try, tok::kw_catch, tok::kw___finally,
337 tok::kw_for, tok::r_brace) ||
338 Line.First->is(Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000339 if (!Style.AllowShortBlocksOnASingleLine)
340 return 0;
341 if (!Style.AllowShortIfStatementsOnASingleLine &&
342 Line.First->is(tok::kw_if))
343 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;
365 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
366 !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;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000449 const SmallVectorImpl<AnnotatedLine*>::const_iterator End;
450
451 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) {}
481 virtual ~LineFormatter() {}
482
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
533 // Cannot merge multiple statements into a single line.
534 if (Previous.Children.size() > 1)
535 return false;
536
537 // Cannot merge into one line if this line ends on a comment.
538 if (Previous.is(tok::comment))
539 return false;
540
541 // We can't put the closing "}" on a line with a trailing comment.
542 if (Previous.Children[0]->Last->isTrailingComment())
543 return false;
544
545 // If the child line exceeds the column limit, we wouldn't want to merge it.
546 // We add +2 for the trailing " }".
547 if (Style.ColumnLimit > 0 &&
548 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
549 Style.ColumnLimit)
550 return false;
551
552 if (!DryRun) {
553 Whitespaces->replaceWhitespace(
554 *Previous.Children[0]->First,
555 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
556 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
557 }
558 Penalty += formatLine(*Previous.Children[0], State.Column + 1, DryRun);
559
560 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
561 return true;
562 }
563
564 ContinuationIndenter *Indenter;
565
566private:
567 WhitespaceManager *Whitespaces;
568 const FormatStyle &Style;
569 UnwrappedLineFormatter *BlockFormatter;
570};
571
572/// \brief Formatter that keeps the existing line breaks.
573class NoColumnLimitLineFormatter : public LineFormatter {
574public:
575 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
576 WhitespaceManager *Whitespaces,
577 const FormatStyle &Style,
578 UnwrappedLineFormatter *BlockFormatter)
579 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
580
581 /// \brief Formats the line, simply keeping all of the input's line breaking
582 /// decisions.
583 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
584 bool DryRun) override {
585 assert(!DryRun);
586 LineState State =
587 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
588 while (State.NextToken) {
589 bool Newline =
590 Indenter->mustBreak(State) ||
591 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
592 unsigned Penalty = 0;
593 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
594 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
595 }
596 return 0;
597 }
598};
599
600/// \brief Formatter that puts all tokens into a single line without breaks.
601class NoLineBreakFormatter : public LineFormatter {
602public:
603 NoLineBreakFormatter(ContinuationIndenter *Indenter,
604 WhitespaceManager *Whitespaces, const FormatStyle &Style,
605 UnwrappedLineFormatter *BlockFormatter)
606 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
607
608 /// \brief Puts all tokens into a single line.
609 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
610 bool DryRun) {
611 unsigned Penalty = 0;
612 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
613 while (State.NextToken) {
614 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
615 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
616 }
617 return Penalty;
618 }
619};
620
621/// \brief Finds the best way to break lines.
622class OptimizingLineFormatter : public LineFormatter {
623public:
624 OptimizingLineFormatter(ContinuationIndenter *Indenter,
625 WhitespaceManager *Whitespaces,
626 const FormatStyle &Style,
627 UnwrappedLineFormatter *BlockFormatter)
628 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
629
630 /// \brief Formats the line by finding the best line breaks with line lengths
631 /// below the column limit.
632 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
633 bool DryRun) {
634 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
635
636 // If the ObjC method declaration does not fit on a line, we should format
637 // it with one arg per line.
638 if (State.Line->Type == LT_ObjCMethodDecl)
639 State.Stack.back().BreakBeforeParameter = true;
640
641 // Find best solution in solution space.
642 return analyzeSolutionSpace(State, DryRun);
643 }
644
645private:
646 struct CompareLineStatePointers {
647 bool operator()(LineState *obj1, LineState *obj2) const {
648 return *obj1 < *obj2;
649 }
650 };
651
652 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
653 ///
654 /// In case of equal penalties, we want to prefer states that were inserted
655 /// first. During state generation we make sure that we insert states first
656 /// that break the line as late as possible.
657 typedef std::pair<unsigned, unsigned> OrderedPenalty;
658
659 /// \brief An edge in the solution space from \c Previous->State to \c State,
660 /// inserting a newline dependent on the \c NewLine.
661 struct StateNode {
662 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
663 : State(State), NewLine(NewLine), Previous(Previous) {}
664 LineState State;
665 bool NewLine;
666 StateNode *Previous;
667 };
668
669 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
670 /// \c State has the given \c OrderedPenalty.
671 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
672
673 /// \brief The BFS queue type.
674 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
675 std::greater<QueueItem>> QueueType;
676
677 /// \brief Analyze the entire solution space starting from \p InitialState.
678 ///
679 /// This implements a variant of Dijkstra's algorithm on the graph that spans
680 /// the solution space (\c LineStates are the nodes). The algorithm tries to
681 /// find the shortest path (the one with lowest penalty) from \p InitialState
682 /// to a state where all tokens are placed. Returns the penalty.
683 ///
684 /// If \p DryRun is \c false, directly applies the changes.
685 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
686 std::set<LineState *, CompareLineStatePointers> Seen;
687
688 // Increasing count of \c StateNode items we have created. This is used to
689 // create a deterministic order independent of the container.
690 unsigned Count = 0;
691 QueueType Queue;
692
693 // Insert start element into queue.
694 StateNode *Node =
695 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
696 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
697 ++Count;
698
699 unsigned Penalty = 0;
700
701 // While not empty, take first element and follow edges.
702 while (!Queue.empty()) {
703 Penalty = Queue.top().first.first;
704 StateNode *Node = Queue.top().second;
705 if (!Node->State.NextToken) {
706 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
707 break;
708 }
709 Queue.pop();
710
711 // Cut off the analysis of certain solutions if the analysis gets too
712 // complex. See description of IgnoreStackForComparison.
713 if (Count > 10000)
714 Node->State.IgnoreStackForComparison = true;
715
716 if (!Seen.insert(&Node->State).second)
717 // State already examined with lower penalty.
718 continue;
719
720 FormatDecision LastFormat = Node->State.NextToken->Decision;
721 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
722 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
723 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
724 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
725 }
726
727 if (Queue.empty()) {
728 // We were unable to find a solution, do nothing.
729 // FIXME: Add diagnostic?
730 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
731 return 0;
732 }
733
734 // Reconstruct the solution.
735 if (!DryRun)
736 reconstructPath(InitialState, Queue.top().second);
737
738 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
739 DEBUG(llvm::dbgs() << "---\n");
740
741 return Penalty;
742 }
743
744 /// \brief Add the following state to the analysis queue \c Queue.
745 ///
746 /// Assume the current state is \p PreviousNode and has been reached with a
747 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
748 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
749 bool NewLine, unsigned *Count, QueueType *Queue) {
750 if (NewLine && !Indenter->canBreak(PreviousNode->State))
751 return;
752 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
753 return;
754
755 StateNode *Node = new (Allocator.Allocate())
756 StateNode(PreviousNode->State, NewLine, PreviousNode);
757 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
758 return;
759
760 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
761
762 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
763 ++(*Count);
764 }
765
766 /// \brief Applies the best formatting by reconstructing the path in the
767 /// solution space that leads to \c Best.
768 void reconstructPath(LineState &State, StateNode *Best) {
769 std::deque<StateNode *> Path;
770 // We do not need a break before the initial token.
771 while (Best->Previous) {
772 Path.push_front(Best);
773 Best = Best->Previous;
774 }
775 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
776 I != E; ++I) {
777 unsigned Penalty = 0;
778 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
779 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
780
781 DEBUG({
782 printLineState((*I)->Previous->State);
783 if ((*I)->NewLine) {
784 llvm::dbgs() << "Penalty for placing "
785 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
786 << Penalty << "\n";
787 }
788 });
789 }
790 }
791
792 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
793};
794
Daniel Jasper0df50932014-12-10 19:00:42 +0000795} // namespace
796
797unsigned
798UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
799 bool DryRun, int AdditionalIndent,
800 bool FixBadIndentation) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000801 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +0000802
803 // Try to look up already computed penalty in DryRun-mode.
804 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
805 &Lines, AdditionalIndent);
806 auto CacheIt = PenaltyCache.find(CacheKey);
807 if (DryRun && CacheIt != PenaltyCache.end())
808 return CacheIt->second;
809
810 assert(!Lines.empty());
811 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000812 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
813 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000814 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000815 const AnnotatedLine *NextLine = nullptr;
816 for (const AnnotatedLine *Line =
817 Joiner.getNextMergedLine(DryRun, IndentTracker);
818 Line; Line = NextLine) {
819 const AnnotatedLine &TheLine = *Line;
820 unsigned Indent = IndentTracker.getIndent();
Daniel Jasper0df50932014-12-10 19:00:42 +0000821 bool FixIndentation =
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000822 FixBadIndentation && (Indent != TheLine.First->OriginalColumn);
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000823 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000824 // We cannot format this line; if the reason is that the line had a
825 // parsing error, remember that.
826 if (ShouldFormat && TheLine.Type == LT_Invalid && IncompleteFormat)
827 *IncompleteFormat = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000828
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000829 if (ShouldFormat && TheLine.Type != LT_Invalid) {
830 if (!DryRun)
831 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
832 TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +0000833
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000834 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
835 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
836 bool FitsIntoOneLine =
837 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
838 TheLine.Type == LT_ImportStatement;
839
840 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000841 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
842 .formatLine(TheLine, Indent, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000843 else if (FitsIntoOneLine)
844 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
845 .formatLine(TheLine, Indent, DryRun);
846 else
Manuel Klimekd3585db2015-05-11 08:21:35 +0000847 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
848 .formatLine(TheLine, Indent, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000849 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000850 // If no token in the current line is affected, we still need to format
851 // affected children.
852 if (TheLine.ChildrenAffected)
853 format(TheLine.Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000854
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000855 // Adapt following lines on the current indent level to the same level
856 // unless the current \c AnnotatedLine is not at the beginning of a line.
857 bool StartsNewLine =
858 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
859 if (StartsNewLine)
860 IndentTracker.adjustToUnmodifiedLine(TheLine);
861 if (!DryRun) {
862 bool ReformatLeadingWhitespace =
863 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
864 TheLine.LeadingEmptyLinesAffected);
865 // Format the first token.
866 if (ReformatLeadingWhitespace)
867 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
868 TheLine.First->OriginalColumn,
869 TheLine.InPPDirective);
870 else
871 Whitespaces->addUntouchableToken(*TheLine.First,
872 TheLine.InPPDirective);
873
874 // Notify the WhitespaceManager about the unchanged whitespace.
875 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +0000876 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +0000877 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000878 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasper0df50932014-12-10 19:00:42 +0000879 }
Daniel Jasperd1c13732015-01-23 19:37:25 +0000880 if (!DryRun)
881 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000882 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +0000883 }
884 PenaltyCache[CacheKey] = Penalty;
885 return Penalty;
886}
887
Daniel Jasper0df50932014-12-10 19:00:42 +0000888void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
889 const AnnotatedLine *PreviousLine,
890 unsigned IndentLevel,
891 unsigned Indent,
892 bool InPPDirective) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000893 if (RootToken.is(tok::eof)) {
894 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
895 Whitespaces->replaceWhitespace(RootToken, Newlines, /*IndentLevel=*/0,
896 /*Spaces=*/0, /*TargetColumn=*/0);
897 return;
898 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000899 unsigned Newlines =
900 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
901 // Remove empty lines before "}" where applicable.
902 if (RootToken.is(tok::r_brace) &&
903 (!RootToken.Next ||
904 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
905 Newlines = std::min(Newlines, 1u);
906 if (Newlines == 0 && !RootToken.IsFirst)
907 Newlines = 1;
908 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
909 Newlines = 0;
910
911 // Remove empty lines after "{".
912 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
913 PreviousLine->Last->is(tok::l_brace) &&
914 PreviousLine->First->isNot(tok::kw_namespace) &&
915 !startsExternCBlock(*PreviousLine))
916 Newlines = 1;
917
918 // Insert extra new line before access specifiers.
919 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
920 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
921 ++Newlines;
922
923 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +0000924 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
925 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +0000926 Newlines = std::min(1u, Newlines);
927
928 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
929 Indent, InPPDirective &&
930 !RootToken.HasUnescapedNewline);
931}
932
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000933unsigned
934UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
935 const AnnotatedLine *NextLine) const {
936 // In preprocessor directives reserve two chars for trailing " \" if the
937 // next line continues the preprocessor directive.
938 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +0000939 InPPDirective &&
940 // If there is no next line, this is likely a child line and the parent
941 // continues the preprocessor directive.
942 (!NextLine ||
943 (NextLine->InPPDirective &&
944 // If there is an unescaped newline between this line and the next, the
945 // next line starts a new preprocessor directive.
946 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000947 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +0000948}
949
Daniel Jasper0df50932014-12-10 19:00:42 +0000950} // namespace format
951} // namespace clang