blob: 253f89da9d14ba4cfc97bf1b825e1ad903983498 [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
Francois Ferrande56a8292017-06-14 12:29:47 +000069 /// \brief Update the indent state given that \p Line indent should be
70 /// skipped.
71 void skipLine(const AnnotatedLine &Line) {
72 while (IndentForLevel.size() <= Line.Level)
73 IndentForLevel.push_back(Indent);
74 }
75
Manuel Klimek3d3ea842015-05-12 09:23:57 +000076 /// \brief Update the level indent to adapt to the given \p Line.
77 ///
78 /// When a line is not formatted, we move the subsequent lines on the same
79 /// level to the same indent.
80 /// Note that \c nextLine must have been called before this method.
81 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
82 unsigned LevelIndent = Line.First->OriginalColumn;
83 if (static_cast<int>(LevelIndent) - Offset >= 0)
84 LevelIndent -= Offset;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000085 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
Manuel Klimek3d3ea842015-05-12 09:23:57 +000086 !Line.InPPDirective)
87 IndentForLevel[Line.Level] = LevelIndent;
88 }
89
90private:
91 /// \brief Get the offset of the line relatively to the level.
92 ///
93 /// For example, 'public:' labels in classes are offset by 1 or 2
94 /// characters to the left from their level.
95 int getIndentOffset(const FormatToken &RootToken) {
96 if (Style.Language == FormatStyle::LK_Java ||
97 Style.Language == FormatStyle::LK_JavaScript)
98 return 0;
99 if (RootToken.isAccessSpecifier(false) ||
100 RootToken.isObjCAccessSpecifier() ||
Daniel Jaspera00de632015-12-01 12:05:04 +0000101 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
102 RootToken.Next && RootToken.Next->is(tok::colon)))
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000103 return Style.AccessModifierOffset;
104 return 0;
105 }
106
107 /// \brief Get the indent of \p Level from \p IndentForLevel.
108 ///
109 /// \p IndentForLevel must contain the indent for the level \c l
110 /// at \p IndentForLevel[l], or a value < 0 if the indent for
111 /// that level is unknown.
112 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
113 if (IndentForLevel[Level] != -1)
114 return IndentForLevel[Level];
115 if (Level == 0)
116 return 0;
117 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
118 }
119
120 const FormatStyle &Style;
121 const AdditionalKeywords &Keywords;
Daniel Jasper56807c12015-05-12 11:14:06 +0000122 const unsigned AdditionalIndent;
Daniel Jasper5fc133e2015-05-12 10:16:02 +0000123
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000124 /// \brief The indent in characters for each level.
125 std::vector<int> IndentForLevel;
126
127 /// \brief Offset of the current line relative to the indent level.
128 ///
129 /// For example, the 'public' keywords is often indented with a negative
130 /// offset.
131 int Offset = 0;
132
133 /// \brief The current line's indent.
134 unsigned Indent = 0;
135};
136
Francois Ferrande56a8292017-06-14 12:29:47 +0000137bool isNamespaceDeclaration(const AnnotatedLine *Line) {
138 const FormatToken *NamespaceTok = Line->First;
Francois Ferrandad722562017-06-30 20:25:55 +0000139 return NamespaceTok && NamespaceTok->getNamespaceToken();
Francois Ferrande56a8292017-06-14 12:29:47 +0000140}
141
142bool isEndOfNamespace(const AnnotatedLine *Line,
143 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
144 if (!Line->startsWith(tok::r_brace))
145 return false;
146 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
147 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
148 return false;
149 assert(StartLineIndex < AnnotatedLines.size());
150 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
151}
152
Daniel Jasper0df50932014-12-10 19:00:42 +0000153class LineJoiner {
154public:
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000155 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
156 const SmallVectorImpl<AnnotatedLine *> &Lines)
Francois Ferrande56a8292017-06-14 12:29:47 +0000157 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
158 AnnotatedLines(Lines) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000159
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000160 /// \brief Returns the next line, merging multiple lines into one if possible.
161 const AnnotatedLine *getNextMergedLine(bool DryRun,
162 LevelIndentTracker &IndentTracker) {
163 if (Next == End)
164 return nullptr;
165 const AnnotatedLine *Current = *Next;
166 IndentTracker.nextLine(*Current);
Manuel Klimek89628f62017-09-20 09:51:03 +0000167 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000168 if (MergedLines > 0 && Style.ColumnLimit == 0)
169 // Disallow line merging if there is a break at the start of one of the
170 // input lines.
171 for (unsigned i = 0; i < MergedLines; ++i)
172 if (Next[i + 1]->First->NewlinesBefore > 0)
173 MergedLines = 0;
174 if (!DryRun)
175 for (unsigned i = 0; i < MergedLines; ++i)
Cameron Desrochers1991e5d2016-11-15 15:07:07 +0000176 join(*Next[0], *Next[i + 1]);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000177 Next = Next + MergedLines + 1;
178 return Current;
179 }
180
181private:
Daniel Jasper0df50932014-12-10 19:00:42 +0000182 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
183 unsigned
Francois Ferrande56a8292017-06-14 12:29:47 +0000184 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
Daniel Jasper0df50932014-12-10 19:00:42 +0000185 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
186 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
Francois Ferrande56a8292017-06-14 12:29:47 +0000187 const unsigned Indent = IndentTracker.getIndent();
188
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000189 // Can't join the last line with anything.
190 if (I + 1 == E)
191 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000192 // We can never merge stuff if there are trailing line comments.
193 const AnnotatedLine *TheLine = *I;
194 if (TheLine->Last->is(TT_LineComment))
195 return 0;
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000196 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
197 return 0;
198 if (TheLine->InPPDirective &&
199 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
200 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000201
202 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
203 return 0;
204
205 unsigned Limit =
206 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
207 // If we already exceed the column limit, we set 'Limit' to 0. The different
208 // tryMerge..() functions can then decide whether to still do merging.
209 Limit = TheLine->Last->TotalLength > Limit
210 ? 0
211 : Limit - TheLine->Last->TotalLength;
212
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000213 if (TheLine->Last->is(TT_FunctionLBrace) &&
214 TheLine->First == TheLine->Last &&
Francois Ferrandad722562017-06-30 20:25:55 +0000215 !Style.BraceWrapping.SplitEmptyFunction &&
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000216 I[1]->First->is(tok::r_brace))
217 return tryMergeSimpleBlock(I, E, Limit);
218
Francois Ferrandad722562017-06-30 20:25:55 +0000219 // Handle empty record blocks where the brace has already been wrapped
220 if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
221 I != AnnotatedLines.begin()) {
222 bool EmptyBlock = I[1]->First->is(tok::r_brace);
223
224 const FormatToken *Tok = I[-1]->First;
225 if (Tok && Tok->is(tok::comment))
226 Tok = Tok->getNextNonComment();
227
228 if (Tok && Tok->getNamespaceToken())
229 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
Manuel Klimek89628f62017-09-20 09:51:03 +0000230 ? tryMergeSimpleBlock(I, E, Limit)
231 : 0;
Francois Ferrandad722562017-06-30 20:25:55 +0000232
233 if (Tok && Tok->is(tok::kw_typedef))
234 Tok = Tok->getNextNonComment();
235 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000236 tok::kw_extern, Keywords.kw_interface))
Francois Ferrandad722562017-06-30 20:25:55 +0000237 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000238 ? tryMergeSimpleBlock(I, E, Limit)
239 : 0;
Francois Ferrandad722562017-06-30 20:25:55 +0000240 }
241
Daniel Jasper0df50932014-12-10 19:00:42 +0000242 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
243 // If necessary, change to something smarter.
244 bool MergeShortFunctions =
245 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper20580fd2015-06-11 13:31:45 +0000246 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000247 I[1]->First->is(tok::r_brace)) ||
Francois Ferrandd3f0e3d2017-06-21 13:56:02 +0000248 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000249 TheLine->Level != 0);
250
Francois Ferrande56a8292017-06-14 12:29:47 +0000251 if (Style.CompactNamespaces) {
252 if (isNamespaceDeclaration(TheLine)) {
253 int i = 0;
254 unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
255 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
256 closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
257 I[i + 1]->Last->TotalLength < Limit;
258 i++, closingLine--) {
259 // No extra indent for compacted namespaces
260 IndentTracker.skipLine(*I[i + 1]);
261
262 Limit -= I[i + 1]->Last->TotalLength;
263 }
264 return i;
265 }
266
267 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
268 int i = 0;
269 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
270 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
271 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
272 i++, openingLine--) {
273 // No space between consecutive braces
274 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
275
276 // Indent like the outer-most namespace
277 IndentTracker.nextLine(*I[i + 1]);
278 }
279 return i;
280 }
281 }
282
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000283 // Try to merge a function block with left brace unwrapped
Daniel Jasper0df50932014-12-10 19:00:42 +0000284 if (TheLine->Last->is(TT_FunctionLBrace) &&
285 TheLine->First != TheLine->Last) {
286 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
287 }
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000288 // Try to merge a control statement block with left brace unwrapped
289 if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
290 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
291 return Style.AllowShortBlocksOnASingleLine
Daniel Jasper0df50932014-12-10 19:00:42 +0000292 ? tryMergeSimpleBlock(I, E, Limit)
293 : 0;
294 }
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000295 // Try to merge a control statement block with left brace wrapped
296 if (I[1]->First->is(tok::l_brace) &&
297 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
298 return Style.BraceWrapping.AfterControlStatement
299 ? tryMergeSimpleBlock(I, E, Limit)
300 : 0;
301 }
302 // Try to merge either empty or one-line block if is precedeed by control
303 // statement token
304 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
305 I != AnnotatedLines.begin() &&
306 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
Krasimir Georgievbf4cdda2018-01-19 16:12:37 +0000307 unsigned MergedLines = 0;
308 if (Style.AllowShortBlocksOnASingleLine) {
309 MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
310 // If we managed to merge the block, discard the first merged line
311 // since we are merging starting from I.
312 if (MergedLines > 0)
313 --MergedLines;
314 }
315 return MergedLines;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000316 }
317 // Try to merge a block with left brace wrapped that wasn't yet covered
318 if (TheLine->Last->is(tok::l_brace)) {
319 return !Style.BraceWrapping.AfterFunction ||
Manuel Klimek89628f62017-09-20 09:51:03 +0000320 (I[1]->First->is(tok::r_brace) &&
321 !Style.BraceWrapping.SplitEmptyRecord)
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000322 ? tryMergeSimpleBlock(I, E, Limit)
323 : 0;
324 }
325 // Try to merge a function block with left brace wrapped
Daniel Jasper0df50932014-12-10 19:00:42 +0000326 if (I[1]->First->is(TT_FunctionLBrace) &&
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000327 Style.BraceWrapping.AfterFunction) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000328 if (I[1]->Last->is(TT_LineComment))
329 return 0;
330
331 // Check for Limit <= 2 to account for the " {".
332 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
333 return 0;
334 Limit -= 2;
335
336 unsigned MergedLines = 0;
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000337 if (MergeShortFunctions ||
338 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
339 I[1]->First == I[1]->Last && I + 2 != E &&
340 I[2]->First->is(tok::r_brace))) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000341 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
342 // If we managed to merge the block, count the function header, which is
343 // on a separate line.
344 if (MergedLines > 0)
345 ++MergedLines;
346 }
347 return MergedLines;
348 }
349 if (TheLine->First->is(tok::kw_if)) {
350 return Style.AllowShortIfStatementsOnASingleLine
351 ? tryMergeSimpleControlStatement(I, E, Limit)
352 : 0;
353 }
354 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
355 return Style.AllowShortLoopsOnASingleLine
356 ? tryMergeSimpleControlStatement(I, E, Limit)
357 : 0;
358 }
359 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
360 return Style.AllowShortCaseLabelsOnASingleLine
361 ? tryMergeShortCaseLabels(I, E, Limit)
362 : 0;
363 }
364 if (TheLine->InPPDirective &&
365 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
366 return tryMergeSimplePPDirective(I, E, Limit);
367 }
368 return 0;
369 }
370
Daniel Jasper0df50932014-12-10 19:00:42 +0000371 unsigned
372 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
373 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
374 unsigned Limit) {
375 if (Limit == 0)
376 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000377 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
378 return 0;
379 if (1 + I[1]->Last->TotalLength > Limit)
380 return 0;
381 return 1;
382 }
383
384 unsigned tryMergeSimpleControlStatement(
385 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
386 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
387 if (Limit == 0)
388 return 0;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000389 if (Style.BraceWrapping.AfterControlStatement &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000390 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
391 return 0;
392 if (I[1]->InPPDirective != (*I)->InPPDirective ||
393 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
394 return 0;
395 Limit = limitConsideringMacros(I + 1, E, Limit);
396 AnnotatedLine &Line = **I;
397 if (Line.Last->isNot(tok::r_paren))
398 return 0;
399 if (1 + I[1]->Last->TotalLength > Limit)
400 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000401 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
402 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000403 return 0;
404 // Only inline simple if's (no nested if or else).
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000405 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000406 I[2]->First->is(tok::kw_else))
407 return 0;
408 return 1;
409 }
410
Manuel Klimekd3585db2015-05-11 08:21:35 +0000411 unsigned
412 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
413 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
414 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000415 if (Limit == 0 || I + 1 == E ||
416 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
417 return 0;
418 unsigned NumStmts = 0;
419 unsigned Length = 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000420 bool EndsWithComment = false;
Daniel Jasper0df50932014-12-10 19:00:42 +0000421 bool InPPDirective = I[0]->InPPDirective;
Francois Ferranda64ba702017-07-28 07:56:18 +0000422 const unsigned Level = I[0]->Level;
Daniel Jasper0df50932014-12-10 19:00:42 +0000423 for (; NumStmts < 3; ++NumStmts) {
424 if (I + 1 + NumStmts == E)
425 break;
426 const AnnotatedLine *Line = I[1 + NumStmts];
427 if (Line->InPPDirective != InPPDirective)
428 break;
429 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
430 break;
431 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Francois Ferranda64ba702017-07-28 07:56:18 +0000432 tok::kw_while) ||
433 EndsWithComment)
Daniel Jasper0df50932014-12-10 19:00:42 +0000434 return 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000435 if (Line->First->is(tok::comment)) {
436 if (Level != Line->Level)
437 return 0;
438 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
439 for (; J != E; ++J) {
440 Line = *J;
441 if (Line->InPPDirective != InPPDirective)
442 break;
443 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
444 break;
445 if (Line->First->isNot(tok::comment) || Level != Line->Level)
446 return 0;
447 }
448 break;
449 }
450 if (Line->Last->is(tok::comment))
451 EndsWithComment = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000452 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
453 }
454 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
455 return 0;
456 return NumStmts;
457 }
458
459 unsigned
460 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
461 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
462 unsigned Limit) {
463 AnnotatedLine &Line = **I;
464
465 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000466 // FIXME: If an option to allow short exception handling clauses on a single
467 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000468 if (Style.Language != FormatStyle::LK_Java &&
469 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
470 return 0;
471
472 // Check that the current line allows merging. This depends on whether we
473 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000474 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
Krasimir Georgiev6a1c9d52017-10-02 15:53:37 +0000475 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000476 return 0;
477 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000478 tok::kw___try, tok::kw_catch, tok::kw___finally,
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000479 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000480 if (!Style.AllowShortBlocksOnASingleLine)
481 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000482 // Don't merge when we can't except the case when
483 // the control statement block is empty
Daniel Jasper0df50932014-12-10 19:00:42 +0000484 if (!Style.AllowShortIfStatementsOnASingleLine &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000485 Line.startsWith(tok::kw_if) &&
486 !Style.BraceWrapping.AfterControlStatement &&
487 !I[1]->First->is(tok::r_brace))
488 return 0;
489 if (!Style.AllowShortIfStatementsOnASingleLine &&
490 Line.startsWith(tok::kw_if) &&
491 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
492 !I[2]->First->is(tok::r_brace))
Daniel Jasper0df50932014-12-10 19:00:42 +0000493 return 0;
494 if (!Style.AllowShortLoopsOnASingleLine &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000495 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
496 !Style.BraceWrapping.AfterControlStatement &&
497 !I[1]->First->is(tok::r_brace))
498 return 0;
499 if (!Style.AllowShortLoopsOnASingleLine &&
500 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
501 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
502 !I[2]->First->is(tok::r_brace))
Daniel Jasper0df50932014-12-10 19:00:42 +0000503 return 0;
504 // FIXME: Consider an option to allow short exception handling clauses on
505 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000506 // FIXME: This isn't covered by tests.
507 // FIXME: For catch, __except, __finally the first token on the line
508 // is '}', so this isn't correct here.
509 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
510 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000511 return 0;
512 }
513
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000514 if (Line.Last->is(tok::l_brace)) {
515 FormatToken *Tok = I[1]->First;
516 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
517 (Tok->getNextNonComment() == nullptr ||
518 Tok->getNextNonComment()->is(tok::semi))) {
519 // We merge empty blocks even if the line exceeds the column limit.
520 Tok->SpacesRequiredBefore = 0;
521 Tok->CanBreakBefore = true;
522 return 1;
523 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
524 !startsExternCBlock(Line)) {
525 // We don't merge short records.
Martin Probstc160cfa2017-11-25 09:35:33 +0000526 FormatToken *RecordTok = Line.First;
527 // Skip record modifiers.
528 while (RecordTok->Next &&
529 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
530 Keywords.kw_declare, Keywords.kw_abstract,
531 tok::kw_default))
532 RecordTok = RecordTok->Next;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000533 if (RecordTok &&
534 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
535 Keywords.kw_interface))
536 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000537
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000538 // Check that we still have three lines and they fit into the limit.
539 if (I + 2 == E || I[2]->Type == LT_Invalid)
540 return 0;
541 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper0df50932014-12-10 19:00:42 +0000542
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000543 if (!nextTwoLinesFitInto(I, Limit))
544 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000545
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000546 // Second, check that the next line does not contain any braces - if it
547 // does, readability declines when putting it into a single line.
548 if (I[1]->Last->is(TT_LineComment))
549 return 0;
550 do {
551 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
552 return 0;
553 Tok = Tok->Next;
554 } while (Tok);
555
556 // Last, check that the third line starts with a closing brace.
557 Tok = I[2]->First;
558 if (Tok->isNot(tok::r_brace))
559 return 0;
560
561 // Don't merge "if (a) { .. } else {".
562 if (Tok->Next && Tok->Next->is(tok::kw_else))
563 return 0;
564
565 return 2;
566 }
567 } else if (I[1]->First->is(tok::l_brace)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000568 if (I[1]->Last->is(TT_LineComment))
569 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000570
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000571 // Check for Limit <= 2 to account for the " {".
572 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000573 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000574 Limit -= 2;
575 unsigned MergedLines = 0;
576 if (Style.AllowShortBlocksOnASingleLine ||
577 (I[1]->First == I[1]->Last && I + 2 != E &&
578 I[2]->First->is(tok::r_brace))) {
579 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
580 // If we managed to merge the block, count the statement header, which
581 // is on a separate line.
582 if (MergedLines > 0)
583 ++MergedLines;
584 }
585 return MergedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000586 }
587 return 0;
588 }
589
590 /// Returns the modified column limit for \p I if it is inside a macro and
591 /// needs a trailing '\'.
592 unsigned
593 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
594 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
595 unsigned Limit) {
596 if (I[0]->InPPDirective && I + 1 != E &&
597 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
598 return Limit < 2 ? 0 : Limit - 2;
599 }
600 return Limit;
601 }
602
603 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
604 unsigned Limit) {
605 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
606 return false;
607 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
608 }
609
610 bool containsMustBreak(const AnnotatedLine *Line) {
611 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
612 if (Tok->MustBreakBefore)
613 return true;
614 }
615 return false;
616 }
617
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000618 void join(AnnotatedLine &A, const AnnotatedLine &B) {
619 assert(!A.Last->Next);
620 assert(!B.First->Previous);
621 if (B.Affected)
622 A.Affected = true;
623 A.Last->Next = B.First;
624 B.First->Previous = A.Last;
625 B.First->CanBreakBefore = true;
626 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
627 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
628 Tok->TotalLength += LengthA;
629 A.Last = Tok;
630 }
631 }
632
Daniel Jasper0df50932014-12-10 19:00:42 +0000633 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000634 const AdditionalKeywords &Keywords;
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000635 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000636
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000637 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
Francois Ferrande56a8292017-06-14 12:29:47 +0000638 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000639};
640
Daniel Jasperd1c13732015-01-23 19:37:25 +0000641static void markFinalized(FormatToken *Tok) {
642 for (; Tok; Tok = Tok->Next) {
643 Tok->Finalized = true;
644 for (AnnotatedLine *Child : Tok->Children)
645 markFinalized(Child->First);
646 }
647}
648
Manuel Klimekd3585db2015-05-11 08:21:35 +0000649#ifndef NDEBUG
650static void printLineState(const LineState &State) {
651 llvm::dbgs() << "State: ";
652 for (const ParenState &P : State.Stack) {
653 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
654 << " ";
655 }
656 llvm::dbgs() << State.NextToken->TokenText << "\n";
657}
658#endif
659
660/// \brief Base class for classes that format one \c AnnotatedLine.
661class LineFormatter {
662public:
663 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
664 const FormatStyle &Style,
665 UnwrappedLineFormatter *BlockFormatter)
666 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
667 BlockFormatter(BlockFormatter) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000668 virtual ~LineFormatter() {}
Manuel Klimekd3585db2015-05-11 08:21:35 +0000669
670 /// \brief Formats an \c AnnotatedLine and returns the penalty.
671 ///
672 /// If \p DryRun is \c false, directly applies the changes.
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000673 virtual unsigned formatLine(const AnnotatedLine &Line,
674 unsigned FirstIndent,
675 unsigned FirstStartColumn,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000676 bool DryRun) = 0;
677
678protected:
679 /// \brief If the \p State's next token is an r_brace closing a nested block,
680 /// format the nested block before it.
681 ///
682 /// Returns \c true if all children could be placed successfully and adapts
683 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
684 /// creates changes using \c Whitespaces.
685 ///
686 /// The crucial idea here is that children always get formatted upon
687 /// encountering the closing brace right after the nested block. Now, if we
688 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
689 /// \c false), the entire block has to be kept on the same line (which is only
690 /// possible if it fits on the line, only contains a single statement, etc.
691 ///
692 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
693 /// break after the "{", format all lines with correct indentation and the put
694 /// the closing "}" on yet another new line.
695 ///
696 /// This enables us to keep the simple structure of the
697 /// \c UnwrappedLineFormatter, where we only have two options for each token:
698 /// break or don't break.
699 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
700 unsigned &Penalty) {
701 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
702 FormatToken &Previous = *State.NextToken->Previous;
703 if (!LBrace || LBrace->isNot(tok::l_brace) ||
704 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
705 // The previous token does not open a block. Nothing to do. We don't
706 // assert so that we can simply call this function for all tokens.
707 return true;
708
709 if (NewLine) {
710 int AdditionalIndent = State.Stack.back().Indent -
711 Previous.Children[0]->Level * Style.IndentWidth;
712
713 Penalty +=
714 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
715 /*FixBadIndentation=*/true);
716 return true;
717 }
718
719 if (Previous.Children[0]->First->MustBreakBefore)
720 return false;
721
Manuel Klimekd3585db2015-05-11 08:21:35 +0000722 // Cannot merge into one line if this line ends on a comment.
723 if (Previous.is(tok::comment))
724 return false;
725
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000726 // Cannot merge multiple statements into a single line.
727 if (Previous.Children.size() > 1)
728 return false;
729
730 const AnnotatedLine *Child = Previous.Children[0];
Manuel Klimekd3585db2015-05-11 08:21:35 +0000731 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000732 if (Child->Last->isTrailingComment())
Manuel Klimekd3585db2015-05-11 08:21:35 +0000733 return false;
734
735 // If the child line exceeds the column limit, we wouldn't want to merge it.
736 // We add +2 for the trailing " }".
737 if (Style.ColumnLimit > 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000738 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000739 return false;
740
741 if (!DryRun) {
742 Whitespaces->replaceWhitespace(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000743 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000744 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
745 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000746 Penalty +=
747 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000748
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000749 State.Column += 1 + Child->Last->TotalLength;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000750 return true;
751 }
752
753 ContinuationIndenter *Indenter;
754
755private:
756 WhitespaceManager *Whitespaces;
757 const FormatStyle &Style;
758 UnwrappedLineFormatter *BlockFormatter;
759};
760
761/// \brief Formatter that keeps the existing line breaks.
762class NoColumnLimitLineFormatter : public LineFormatter {
763public:
764 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
765 WhitespaceManager *Whitespaces,
766 const FormatStyle &Style,
767 UnwrappedLineFormatter *BlockFormatter)
768 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
769
770 /// \brief Formats the line, simply keeping all of the input's line breaking
771 /// decisions.
772 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000773 unsigned FirstStartColumn, bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000774 assert(!DryRun);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000775 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
776 &Line, /*DryRun=*/false);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000777 while (State.NextToken) {
778 bool Newline =
779 Indenter->mustBreak(State) ||
780 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
781 unsigned Penalty = 0;
782 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
783 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
784 }
785 return 0;
786 }
787};
788
789/// \brief Formatter that puts all tokens into a single line without breaks.
790class NoLineBreakFormatter : public LineFormatter {
791public:
792 NoLineBreakFormatter(ContinuationIndenter *Indenter,
793 WhitespaceManager *Whitespaces, const FormatStyle &Style,
794 UnwrappedLineFormatter *BlockFormatter)
795 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
796
797 /// \brief Puts all tokens into a single line.
798 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000799 unsigned FirstStartColumn, bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000800 unsigned Penalty = 0;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000801 LineState State =
802 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000803 while (State.NextToken) {
804 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
Krasimir Georgiev994b6c92017-05-18 08:07:52 +0000805 Indenter->addTokenToState(
806 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000807 }
808 return Penalty;
809 }
810};
811
812/// \brief Finds the best way to break lines.
813class OptimizingLineFormatter : public LineFormatter {
814public:
815 OptimizingLineFormatter(ContinuationIndenter *Indenter,
816 WhitespaceManager *Whitespaces,
817 const FormatStyle &Style,
818 UnwrappedLineFormatter *BlockFormatter)
819 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
820
821 /// \brief Formats the line by finding the best line breaks with line lengths
822 /// below the column limit.
823 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000824 unsigned FirstStartColumn, bool DryRun) override {
825 LineState State =
826 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000827
828 // If the ObjC method declaration does not fit on a line, we should format
829 // it with one arg per line.
830 if (State.Line->Type == LT_ObjCMethodDecl)
831 State.Stack.back().BreakBeforeParameter = true;
832
833 // Find best solution in solution space.
834 return analyzeSolutionSpace(State, DryRun);
835 }
836
837private:
838 struct CompareLineStatePointers {
839 bool operator()(LineState *obj1, LineState *obj2) const {
840 return *obj1 < *obj2;
841 }
842 };
843
844 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
845 ///
846 /// In case of equal penalties, we want to prefer states that were inserted
847 /// first. During state generation we make sure that we insert states first
848 /// that break the line as late as possible.
849 typedef std::pair<unsigned, unsigned> OrderedPenalty;
850
851 /// \brief An edge in the solution space from \c Previous->State to \c State,
852 /// inserting a newline dependent on the \c NewLine.
853 struct StateNode {
854 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
855 : State(State), NewLine(NewLine), Previous(Previous) {}
856 LineState State;
857 bool NewLine;
858 StateNode *Previous;
859 };
860
861 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
862 /// \c State has the given \c OrderedPenalty.
863 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
864
865 /// \brief The BFS queue type.
866 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
Manuel Klimek89628f62017-09-20 09:51:03 +0000867 std::greater<QueueItem>>
868 QueueType;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000869
870 /// \brief Analyze the entire solution space starting from \p InitialState.
871 ///
872 /// This implements a variant of Dijkstra's algorithm on the graph that spans
873 /// the solution space (\c LineStates are the nodes). The algorithm tries to
874 /// find the shortest path (the one with lowest penalty) from \p InitialState
875 /// to a state where all tokens are placed. Returns the penalty.
876 ///
877 /// If \p DryRun is \c false, directly applies the changes.
878 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
879 std::set<LineState *, CompareLineStatePointers> Seen;
880
881 // Increasing count of \c StateNode items we have created. This is used to
882 // create a deterministic order independent of the container.
883 unsigned Count = 0;
884 QueueType Queue;
885
886 // Insert start element into queue.
887 StateNode *Node =
888 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
889 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
890 ++Count;
891
892 unsigned Penalty = 0;
893
894 // While not empty, take first element and follow edges.
895 while (!Queue.empty()) {
896 Penalty = Queue.top().first.first;
897 StateNode *Node = Queue.top().second;
898 if (!Node->State.NextToken) {
899 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
900 break;
901 }
902 Queue.pop();
903
904 // Cut off the analysis of certain solutions if the analysis gets too
905 // complex. See description of IgnoreStackForComparison.
Daniel Jasper75bf2032015-10-27 22:55:55 +0000906 if (Count > 50000)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000907 Node->State.IgnoreStackForComparison = true;
908
909 if (!Seen.insert(&Node->State).second)
910 // State already examined with lower penalty.
911 continue;
912
913 FormatDecision LastFormat = Node->State.NextToken->Decision;
914 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
915 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
916 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
917 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
918 }
919
920 if (Queue.empty()) {
921 // We were unable to find a solution, do nothing.
922 // FIXME: Add diagnostic?
923 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
924 return 0;
925 }
926
927 // Reconstruct the solution.
928 if (!DryRun)
929 reconstructPath(InitialState, Queue.top().second);
930
931 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
932 DEBUG(llvm::dbgs() << "---\n");
933
934 return Penalty;
935 }
936
937 /// \brief Add the following state to the analysis queue \c Queue.
938 ///
939 /// Assume the current state is \p PreviousNode and has been reached with a
940 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
941 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
942 bool NewLine, unsigned *Count, QueueType *Queue) {
943 if (NewLine && !Indenter->canBreak(PreviousNode->State))
944 return;
945 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
946 return;
947
948 StateNode *Node = new (Allocator.Allocate())
949 StateNode(PreviousNode->State, NewLine, PreviousNode);
950 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
951 return;
952
953 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
954
955 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
956 ++(*Count);
957 }
958
959 /// \brief Applies the best formatting by reconstructing the path in the
960 /// solution space that leads to \c Best.
961 void reconstructPath(LineState &State, StateNode *Best) {
962 std::deque<StateNode *> Path;
963 // We do not need a break before the initial token.
964 while (Best->Previous) {
965 Path.push_front(Best);
966 Best = Best->Previous;
967 }
968 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
969 I != E; ++I) {
970 unsigned Penalty = 0;
971 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
972 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
973
974 DEBUG({
975 printLineState((*I)->Previous->State);
976 if ((*I)->NewLine) {
977 llvm::dbgs() << "Penalty for placing "
978 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
979 << Penalty << "\n";
980 }
981 });
982 }
983 }
984
985 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
986};
987
Hans Wennborg7eb54642015-09-10 17:07:54 +0000988} // anonymous namespace
Daniel Jasper0df50932014-12-10 19:00:42 +0000989
990unsigned
991UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
992 bool DryRun, int AdditionalIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000993 bool FixBadIndentation,
994 unsigned FirstStartColumn,
995 unsigned NextStartColumn,
996 unsigned LastStartColumn) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000997 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +0000998
999 // Try to look up already computed penalty in DryRun-mode.
1000 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1001 &Lines, AdditionalIndent);
1002 auto CacheIt = PenaltyCache.find(CacheKey);
1003 if (DryRun && CacheIt != PenaltyCache.end())
1004 return CacheIt->second;
1005
1006 assert(!Lines.empty());
1007 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001008 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1009 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +00001010 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001011 const AnnotatedLine *NextLine = nullptr;
Daniel Jasperf67c3242015-11-01 00:27:35 +00001012
1013 // The minimum level of consecutive lines that have been formatted.
1014 unsigned RangeMinLevel = UINT_MAX;
Daniel Jasperf67c3242015-11-01 00:27:35 +00001015
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001016 bool FirstLine = true;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001017 for (const AnnotatedLine *Line =
1018 Joiner.getNextMergedLine(DryRun, IndentTracker);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001019 Line; Line = NextLine, FirstLine = false) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001020 const AnnotatedLine &TheLine = *Line;
1021 unsigned Indent = IndentTracker.getIndent();
Daniel Jasperf67c3242015-11-01 00:27:35 +00001022
1023 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1024 // scope was added. However, we need to carefully stop doing this when we
1025 // exit the scope of affected lines to prevent indenting a the entire
1026 // remaining file if it currently missing a closing brace.
1027 bool ContinueFormatting =
1028 TheLine.Level > RangeMinLevel ||
Daniel Jasperf83834f2015-11-02 20:02:49 +00001029 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
Daniel Jasperf67c3242015-11-01 00:27:35 +00001030
1031 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Daniel Jaspera1036e52015-10-28 01:08:22 +00001032 Indent != TheLine.First->OriginalColumn;
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001033 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001034 // We cannot format this line; if the reason is that the line had a
1035 // parsing error, remember that.
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001036 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1037 Status->FormatComplete = false;
1038 Status->Line =
1039 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1040 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001041
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001042 if (ShouldFormat && TheLine.Type != LT_Invalid) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001043 if (!DryRun) {
1044 bool LastLine = Line->First->is(tok::eof);
1045 formatFirstToken(TheLine, PreviousLine,
1046 Indent,
1047 LastLine ? LastStartColumn : NextStartColumn + Indent);
1048 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001049
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001050 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1051 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1052 bool FitsIntoOneLine =
1053 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
Martin Probst0cd74ee2016-06-13 16:39:50 +00001054 (TheLine.Type == LT_ImportStatement &&
1055 (Style.Language != FormatStyle::LK_JavaScript ||
1056 !Style.JavaScriptWrapImports));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001057 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +00001058 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001059 .formatLine(TheLine, NextStartColumn + Indent,
1060 FirstLine ? FirstStartColumn : 0, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001061 else if (FitsIntoOneLine)
1062 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001063 .formatLine(TheLine, NextStartColumn + Indent,
1064 FirstLine ? FirstStartColumn : 0, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001065 else
Manuel Klimekd3585db2015-05-11 08:21:35 +00001066 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001067 .formatLine(TheLine, NextStartColumn + Indent,
1068 FirstLine ? FirstStartColumn : 0, DryRun);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001069 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
Daniel Jasper0df50932014-12-10 19:00:42 +00001070 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001071 // If no token in the current line is affected, we still need to format
1072 // affected children.
1073 if (TheLine.ChildrenAffected)
Daniel Jasper35ca66d2016-02-29 12:26:20 +00001074 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1075 if (!Tok->Children.empty())
1076 format(Tok->Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +00001077
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001078 // Adapt following lines on the current indent level to the same level
1079 // unless the current \c AnnotatedLine is not at the beginning of a line.
1080 bool StartsNewLine =
1081 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1082 if (StartsNewLine)
1083 IndentTracker.adjustToUnmodifiedLine(TheLine);
1084 if (!DryRun) {
1085 bool ReformatLeadingWhitespace =
1086 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1087 TheLine.LeadingEmptyLinesAffected);
1088 // Format the first token.
1089 if (ReformatLeadingWhitespace)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001090 formatFirstToken(TheLine, PreviousLine,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001091 TheLine.First->OriginalColumn,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001092 TheLine.First->OriginalColumn);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001093 else
1094 Whitespaces->addUntouchableToken(*TheLine.First,
1095 TheLine.InPPDirective);
1096
1097 // Notify the WhitespaceManager about the unchanged whitespace.
1098 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +00001099 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +00001100 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001101 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001102 RangeMinLevel = UINT_MAX;
Daniel Jasper0df50932014-12-10 19:00:42 +00001103 }
Daniel Jasperd1c13732015-01-23 19:37:25 +00001104 if (!DryRun)
1105 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001106 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +00001107 }
1108 PenaltyCache[CacheKey] = Penalty;
1109 return Penalty;
1110}
1111
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001112void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
Daniel Jasper0df50932014-12-10 19:00:42 +00001113 const AnnotatedLine *PreviousLine,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001114 unsigned Indent,
1115 unsigned NewlineIndent) {
Manuel Klimek89628f62017-09-20 09:51:03 +00001116 FormatToken &RootToken = *Line.First;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001117 if (RootToken.is(tok::eof)) {
1118 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001119 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1120 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1121 TokenIndent);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001122 return;
1123 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001124 unsigned Newlines =
1125 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1126 // Remove empty lines before "}" where applicable.
1127 if (RootToken.is(tok::r_brace) &&
1128 (!RootToken.Next ||
1129 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1130 Newlines = std::min(Newlines, 1u);
Martin Probsta004b3f2017-11-17 18:06:33 +00001131 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1132 if (PreviousLine == nullptr && Line.Level > 0)
1133 Newlines = std::min(Newlines, 1u);
Daniel Jasper0df50932014-12-10 19:00:42 +00001134 if (Newlines == 0 && !RootToken.IsFirst)
1135 Newlines = 1;
1136 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1137 Newlines = 0;
1138
1139 // Remove empty lines after "{".
1140 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1141 PreviousLine->Last->is(tok::l_brace) &&
1142 PreviousLine->First->isNot(tok::kw_namespace) &&
1143 !startsExternCBlock(*PreviousLine))
1144 Newlines = 1;
1145
1146 // Insert extra new line before access specifiers.
1147 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1148 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1149 ++Newlines;
1150
1151 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +00001152 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1153 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +00001154 Newlines = std::min(1u, Newlines);
1155
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001156 if (Newlines)
1157 Indent = NewlineIndent;
1158
1159 // Preprocessor directives get indented after the hash, if indented.
1160 if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement)
1161 Indent = 0;
1162
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001163 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1164 Line.InPPDirective &&
1165 !RootToken.HasUnescapedNewline);
Daniel Jasper0df50932014-12-10 19:00:42 +00001166}
1167
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001168unsigned
1169UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1170 const AnnotatedLine *NextLine) const {
1171 // In preprocessor directives reserve two chars for trailing " \" if the
1172 // next line continues the preprocessor directive.
1173 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +00001174 InPPDirective &&
1175 // If there is no next line, this is likely a child line and the parent
1176 // continues the preprocessor directive.
1177 (!NextLine ||
1178 (NextLine->InPPDirective &&
1179 // If there is an unescaped newline between this line and the next, the
1180 // next line starts a new preprocessor directive.
1181 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001182 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +00001183}
1184
Daniel Jasper0df50932014-12-10 19:00:42 +00001185} // namespace format
1186} // namespace clang