blob: 33163f7d0a1b59a41be24c9b48aaca6c2c09afb5 [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
Krasimir Georgiev62103052018-04-19 13:02:15 +000010#include "NamespaceEndCommentsFixer.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000011#include "UnwrappedLineFormatter.h"
12#include "WhitespaceManager.h"
13#include "llvm/Support/Debug.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include <queue>
Daniel Jasper0df50932014-12-10 19:00:42 +000015
16#define DEBUG_TYPE "format-formatter"
17
18namespace clang {
19namespace format {
20
21namespace {
22
23bool startsExternCBlock(const AnnotatedLine &Line) {
24 const FormatToken *Next = Line.First->getNextNonComment();
25 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000026 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
Daniel Jasper0df50932014-12-10 19:00:42 +000027 NextNext && NextNext->is(tok::l_brace);
28}
29
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030/// Tracks the indent level of \c AnnotatedLines across levels.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000031///
32/// \c nextLine must be called for each \c AnnotatedLine, after which \c
33/// getIndent() will return the indent for the last line \c nextLine was called
34/// with.
35/// If the line is not formatted (and thus the indent does not change), calling
36/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
37/// subsequent lines on the same level to be indented at the same level as the
38/// given line.
39class LevelIndentTracker {
40public:
41 LevelIndentTracker(const FormatStyle &Style,
42 const AdditionalKeywords &Keywords, unsigned StartLevel,
43 int AdditionalIndent)
Daniel Jasper5fc133e2015-05-12 10:16:02 +000044 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000045 for (unsigned i = 0; i != StartLevel; ++i)
46 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
47 }
48
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049 /// Returns the indent for the current line.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000050 unsigned getIndent() const { return Indent; }
51
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Update the indent state given that \p Line is going to be formatted
Manuel Klimek3d3ea842015-05-12 09:23:57 +000053 /// next.
54 void nextLine(const AnnotatedLine &Line) {
55 Offset = getIndentOffset(*Line.First);
Manuel Klimekf0c95b32015-06-11 10:14:13 +000056 // Update the indent level cache size so that we can rely on it
57 // having the right size in adjustToUnmodifiedline.
58 while (IndentForLevel.size() <= Line.Level)
59 IndentForLevel.push_back(-1);
Manuel Klimek3d3ea842015-05-12 09:23:57 +000060 if (Line.InPPDirective) {
Daniel Jasper5fc133e2015-05-12 10:16:02 +000061 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
Manuel Klimek3d3ea842015-05-12 09:23:57 +000062 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000063 IndentForLevel.resize(Line.Level + 1);
64 Indent = getIndent(IndentForLevel, Line.Level);
65 }
66 if (static_cast<int>(Indent) + Offset >= 0)
67 Indent += Offset;
68 }
69
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Update the indent state given that \p Line indent should be
Francois Ferrande56a8292017-06-14 12:29:47 +000071 /// skipped.
72 void skipLine(const AnnotatedLine &Line) {
73 while (IndentForLevel.size() <= Line.Level)
74 IndentForLevel.push_back(Indent);
75 }
76
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000077 /// Update the level indent to adapt to the given \p Line.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000078 ///
79 /// When a line is not formatted, we move the subsequent lines on the same
80 /// level to the same indent.
81 /// Note that \c nextLine must have been called before this method.
82 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
83 unsigned LevelIndent = Line.First->OriginalColumn;
84 if (static_cast<int>(LevelIndent) - Offset >= 0)
85 LevelIndent -= Offset;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000086 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
Manuel Klimek3d3ea842015-05-12 09:23:57 +000087 !Line.InPPDirective)
88 IndentForLevel[Line.Level] = LevelIndent;
89 }
90
91private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Get the offset of the line relatively to the level.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000093 ///
94 /// For example, 'public:' labels in classes are offset by 1 or 2
95 /// characters to the left from their level.
96 int getIndentOffset(const FormatToken &RootToken) {
97 if (Style.Language == FormatStyle::LK_Java ||
98 Style.Language == FormatStyle::LK_JavaScript)
99 return 0;
100 if (RootToken.isAccessSpecifier(false) ||
101 RootToken.isObjCAccessSpecifier() ||
Daniel Jaspera00de632015-12-01 12:05:04 +0000102 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
103 RootToken.Next && RootToken.Next->is(tok::colon)))
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000104 return Style.AccessModifierOffset;
105 return 0;
106 }
107
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000108 /// Get the indent of \p Level from \p IndentForLevel.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000109 ///
110 /// \p IndentForLevel must contain the indent for the level \c l
111 /// at \p IndentForLevel[l], or a value < 0 if the indent for
112 /// that level is unknown.
113 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
114 if (IndentForLevel[Level] != -1)
115 return IndentForLevel[Level];
116 if (Level == 0)
117 return 0;
118 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
119 }
120
121 const FormatStyle &Style;
122 const AdditionalKeywords &Keywords;
Daniel Jasper56807c12015-05-12 11:14:06 +0000123 const unsigned AdditionalIndent;
Daniel Jasper5fc133e2015-05-12 10:16:02 +0000124
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000125 /// The indent in characters for each level.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000126 std::vector<int> IndentForLevel;
127
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000128 /// Offset of the current line relative to the indent level.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000129 ///
130 /// For example, the 'public' keywords is often indented with a negative
131 /// offset.
132 int Offset = 0;
133
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000134 /// The current line's indent.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000135 unsigned Indent = 0;
136};
137
Francois Ferrande56a8292017-06-14 12:29:47 +0000138bool isNamespaceDeclaration(const AnnotatedLine *Line) {
139 const FormatToken *NamespaceTok = Line->First;
Francois Ferrandad722562017-06-30 20:25:55 +0000140 return NamespaceTok && NamespaceTok->getNamespaceToken();
Francois Ferrande56a8292017-06-14 12:29:47 +0000141}
142
143bool isEndOfNamespace(const AnnotatedLine *Line,
144 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
145 if (!Line->startsWith(tok::r_brace))
146 return false;
147 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
148 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
149 return false;
150 assert(StartLineIndex < AnnotatedLines.size());
151 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
152}
153
Daniel Jasper0df50932014-12-10 19:00:42 +0000154class LineJoiner {
155public:
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000156 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
157 const SmallVectorImpl<AnnotatedLine *> &Lines)
Francois Ferrande56a8292017-06-14 12:29:47 +0000158 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
159 AnnotatedLines(Lines) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000161 /// Returns the next line, merging multiple lines into one if possible.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000162 const AnnotatedLine *getNextMergedLine(bool DryRun,
163 LevelIndentTracker &IndentTracker) {
164 if (Next == End)
165 return nullptr;
166 const AnnotatedLine *Current = *Next;
167 IndentTracker.nextLine(*Current);
Manuel Klimek89628f62017-09-20 09:51:03 +0000168 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000169 if (MergedLines > 0 && Style.ColumnLimit == 0)
170 // Disallow line merging if there is a break at the start of one of the
171 // input lines.
172 for (unsigned i = 0; i < MergedLines; ++i)
173 if (Next[i + 1]->First->NewlinesBefore > 0)
174 MergedLines = 0;
175 if (!DryRun)
176 for (unsigned i = 0; i < MergedLines; ++i)
Cameron Desrochers1991e5d2016-11-15 15:07:07 +0000177 join(*Next[0], *Next[i + 1]);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000178 Next = Next + MergedLines + 1;
179 return Current;
180 }
181
182private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000183 /// Calculates how many lines can be merged into 1 starting at \p I.
Daniel Jasper0df50932014-12-10 19:00:42 +0000184 unsigned
Francois Ferrande56a8292017-06-14 12:29:47 +0000185 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
Daniel Jasper0df50932014-12-10 19:00:42 +0000186 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
187 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
Francois Ferrande56a8292017-06-14 12:29:47 +0000188 const unsigned Indent = IndentTracker.getIndent();
189
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000190 // Can't join the last line with anything.
191 if (I + 1 == E)
192 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000193 // We can never merge stuff if there are trailing line comments.
194 const AnnotatedLine *TheLine = *I;
195 if (TheLine->Last->is(TT_LineComment))
196 return 0;
Daniel Jasper9ecb0e92015-03-13 13:32:11 +0000197 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
198 return 0;
199 if (TheLine->InPPDirective &&
200 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
201 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000202
203 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
204 return 0;
205
206 unsigned Limit =
207 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
208 // If we already exceed the column limit, we set 'Limit' to 0. The different
209 // tryMerge..() functions can then decide whether to still do merging.
210 Limit = TheLine->Last->TotalLength > Limit
211 ? 0
212 : Limit - TheLine->Last->TotalLength;
213
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000214 if (TheLine->Last->is(TT_FunctionLBrace) &&
215 TheLine->First == TheLine->Last &&
Francois Ferrandad722562017-06-30 20:25:55 +0000216 !Style.BraceWrapping.SplitEmptyFunction &&
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000217 I[1]->First->is(tok::r_brace))
218 return tryMergeSimpleBlock(I, E, Limit);
219
Francois Ferrandad722562017-06-30 20:25:55 +0000220 // Handle empty record blocks where the brace has already been wrapped
221 if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
222 I != AnnotatedLines.begin()) {
223 bool EmptyBlock = I[1]->First->is(tok::r_brace);
224
225 const FormatToken *Tok = I[-1]->First;
226 if (Tok && Tok->is(tok::comment))
227 Tok = Tok->getNextNonComment();
228
229 if (Tok && Tok->getNamespaceToken())
230 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
Manuel Klimek89628f62017-09-20 09:51:03 +0000231 ? tryMergeSimpleBlock(I, E, Limit)
232 : 0;
Francois Ferrandad722562017-06-30 20:25:55 +0000233
234 if (Tok && Tok->is(tok::kw_typedef))
235 Tok = Tok->getNextNonComment();
236 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000237 tok::kw_extern, Keywords.kw_interface))
Francois Ferrandad722562017-06-30 20:25:55 +0000238 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
Krasimir Georgievd6ce9372017-09-15 11:23:50 +0000239 ? tryMergeSimpleBlock(I, E, Limit)
240 : 0;
Francois Ferrandad722562017-06-30 20:25:55 +0000241 }
242
Daniel Jasper0df50932014-12-10 19:00:42 +0000243 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
244 // If necessary, change to something smarter.
245 bool MergeShortFunctions =
246 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper20580fd2015-06-11 13:31:45 +0000247 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000248 I[1]->First->is(tok::r_brace)) ||
Francois Ferrandd3f0e3d2017-06-21 13:56:02 +0000249 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000250 TheLine->Level != 0);
251
Francois Ferrande56a8292017-06-14 12:29:47 +0000252 if (Style.CompactNamespaces) {
253 if (isNamespaceDeclaration(TheLine)) {
254 int i = 0;
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000255 unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
Francois Ferrande56a8292017-06-14 12:29:47 +0000256 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000257 closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
Francois Ferrande56a8292017-06-14 12:29:47 +0000258 I[i + 1]->Last->TotalLength < Limit;
259 i++, closingLine--) {
260 // No extra indent for compacted namespaces
261 IndentTracker.skipLine(*I[i + 1]);
262
263 Limit -= I[i + 1]->Last->TotalLength;
264 }
265 return i;
266 }
267
268 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
269 int i = 0;
270 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
271 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
272 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
273 i++, openingLine--) {
274 // No space between consecutive braces
275 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
276
277 // Indent like the outer-most namespace
278 IndentTracker.nextLine(*I[i + 1]);
279 }
280 return i;
281 }
282 }
283
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000284 // Try to merge a function block with left brace unwrapped
Daniel Jasper0df50932014-12-10 19:00:42 +0000285 if (TheLine->Last->is(TT_FunctionLBrace) &&
286 TheLine->First != TheLine->Last) {
287 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
288 }
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000289 // Try to merge a control statement block with left brace unwrapped
290 if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
291 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
292 return Style.AllowShortBlocksOnASingleLine
Daniel Jasper0df50932014-12-10 19:00:42 +0000293 ? tryMergeSimpleBlock(I, E, Limit)
294 : 0;
295 }
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000296 // Try to merge a control statement block with left brace wrapped
297 if (I[1]->First->is(tok::l_brace) &&
298 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
299 return Style.BraceWrapping.AfterControlStatement
300 ? tryMergeSimpleBlock(I, E, Limit)
301 : 0;
302 }
303 // Try to merge either empty or one-line block if is precedeed by control
304 // statement token
305 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
306 I != AnnotatedLines.begin() &&
307 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
Krasimir Georgievbf4cdda2018-01-19 16:12:37 +0000308 unsigned MergedLines = 0;
309 if (Style.AllowShortBlocksOnASingleLine) {
310 MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
311 // If we managed to merge the block, discard the first merged line
312 // since we are merging starting from I.
313 if (MergedLines > 0)
314 --MergedLines;
315 }
316 return MergedLines;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000317 }
Francois Ferranda2484b22018-02-27 13:48:27 +0000318 // Don't merge block with left brace wrapped after ObjC special blocks
319 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
320 I[-1]->First->is(tok::at) && I[-1]->First->Next) {
321 tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
322 if (kwId == clang::tok::objc_autoreleasepool ||
323 kwId == clang::tok::objc_synchronized)
324 return 0;
325 }
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000326 // Try to merge a block with left brace wrapped that wasn't yet covered
327 if (TheLine->Last->is(tok::l_brace)) {
328 return !Style.BraceWrapping.AfterFunction ||
Manuel Klimek89628f62017-09-20 09:51:03 +0000329 (I[1]->First->is(tok::r_brace) &&
330 !Style.BraceWrapping.SplitEmptyRecord)
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000331 ? tryMergeSimpleBlock(I, E, Limit)
332 : 0;
333 }
334 // Try to merge a function block with left brace wrapped
Daniel Jasper0df50932014-12-10 19:00:42 +0000335 if (I[1]->First->is(TT_FunctionLBrace) &&
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000336 Style.BraceWrapping.AfterFunction) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000337 if (I[1]->Last->is(TT_LineComment))
338 return 0;
339
340 // Check for Limit <= 2 to account for the " {".
341 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
342 return 0;
343 Limit -= 2;
344
345 unsigned MergedLines = 0;
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000346 if (MergeShortFunctions ||
347 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
348 I[1]->First == I[1]->Last && I + 2 != E &&
349 I[2]->First->is(tok::r_brace))) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000350 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
351 // If we managed to merge the block, count the function header, which is
352 // on a separate line.
353 if (MergedLines > 0)
354 ++MergedLines;
355 }
356 return MergedLines;
357 }
358 if (TheLine->First->is(tok::kw_if)) {
359 return Style.AllowShortIfStatementsOnASingleLine
360 ? tryMergeSimpleControlStatement(I, E, Limit)
361 : 0;
362 }
363 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
364 return Style.AllowShortLoopsOnASingleLine
365 ? tryMergeSimpleControlStatement(I, E, Limit)
366 : 0;
367 }
368 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
369 return Style.AllowShortCaseLabelsOnASingleLine
370 ? tryMergeShortCaseLabels(I, E, Limit)
371 : 0;
372 }
373 if (TheLine->InPPDirective &&
374 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
375 return tryMergeSimplePPDirective(I, E, Limit);
376 }
377 return 0;
378 }
379
Daniel Jasper0df50932014-12-10 19:00:42 +0000380 unsigned
381 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
382 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
383 unsigned Limit) {
384 if (Limit == 0)
385 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000386 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
387 return 0;
388 if (1 + I[1]->Last->TotalLength > Limit)
389 return 0;
390 return 1;
391 }
392
393 unsigned tryMergeSimpleControlStatement(
394 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
395 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
396 if (Limit == 0)
397 return 0;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000398 if (Style.BraceWrapping.AfterControlStatement &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000399 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
400 return 0;
401 if (I[1]->InPPDirective != (*I)->InPPDirective ||
402 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
403 return 0;
404 Limit = limitConsideringMacros(I + 1, E, Limit);
405 AnnotatedLine &Line = **I;
406 if (Line.Last->isNot(tok::r_paren))
407 return 0;
408 if (1 + I[1]->Last->TotalLength > Limit)
409 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000410 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
411 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000412 return 0;
413 // Only inline simple if's (no nested if or else).
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000414 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000415 I[2]->First->is(tok::kw_else))
416 return 0;
417 return 1;
418 }
419
Manuel Klimekd3585db2015-05-11 08:21:35 +0000420 unsigned
421 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
422 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
423 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000424 if (Limit == 0 || I + 1 == E ||
425 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
426 return 0;
427 unsigned NumStmts = 0;
428 unsigned Length = 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000429 bool EndsWithComment = false;
Daniel Jasper0df50932014-12-10 19:00:42 +0000430 bool InPPDirective = I[0]->InPPDirective;
Francois Ferranda64ba702017-07-28 07:56:18 +0000431 const unsigned Level = I[0]->Level;
Daniel Jasper0df50932014-12-10 19:00:42 +0000432 for (; NumStmts < 3; ++NumStmts) {
433 if (I + 1 + NumStmts == E)
434 break;
435 const AnnotatedLine *Line = I[1 + NumStmts];
436 if (Line->InPPDirective != InPPDirective)
437 break;
438 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
439 break;
440 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Francois Ferranda64ba702017-07-28 07:56:18 +0000441 tok::kw_while) ||
442 EndsWithComment)
Daniel Jasper0df50932014-12-10 19:00:42 +0000443 return 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000444 if (Line->First->is(tok::comment)) {
445 if (Level != Line->Level)
446 return 0;
447 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
448 for (; J != E; ++J) {
449 Line = *J;
450 if (Line->InPPDirective != InPPDirective)
451 break;
452 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
453 break;
454 if (Line->First->isNot(tok::comment) || Level != Line->Level)
455 return 0;
456 }
457 break;
458 }
459 if (Line->Last->is(tok::comment))
460 EndsWithComment = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000461 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
462 }
463 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
464 return 0;
465 return NumStmts;
466 }
467
468 unsigned
469 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
470 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
471 unsigned Limit) {
472 AnnotatedLine &Line = **I;
473
474 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000475 // FIXME: If an option to allow short exception handling clauses on a single
476 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000477 if (Style.Language != FormatStyle::LK_Java &&
478 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
479 return 0;
480
481 // Check that the current line allows merging. This depends on whether we
482 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000483 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
Krasimir Georgiev6a1c9d52017-10-02 15:53:37 +0000484 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000485 return 0;
486 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000487 tok::kw___try, tok::kw_catch, tok::kw___finally,
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000488 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000489 if (!Style.AllowShortBlocksOnASingleLine)
490 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000491 // Don't merge when we can't except the case when
492 // the control statement block is empty
Daniel Jasper0df50932014-12-10 19:00:42 +0000493 if (!Style.AllowShortIfStatementsOnASingleLine &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000494 Line.startsWith(tok::kw_if) &&
495 !Style.BraceWrapping.AfterControlStatement &&
496 !I[1]->First->is(tok::r_brace))
497 return 0;
498 if (!Style.AllowShortIfStatementsOnASingleLine &&
499 Line.startsWith(tok::kw_if) &&
500 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
501 !I[2]->First->is(tok::r_brace))
Daniel Jasper0df50932014-12-10 19:00:42 +0000502 return 0;
503 if (!Style.AllowShortLoopsOnASingleLine &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000504 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
505 !Style.BraceWrapping.AfterControlStatement &&
506 !I[1]->First->is(tok::r_brace))
507 return 0;
508 if (!Style.AllowShortLoopsOnASingleLine &&
509 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
510 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
511 !I[2]->First->is(tok::r_brace))
Daniel Jasper0df50932014-12-10 19:00:42 +0000512 return 0;
513 // FIXME: Consider an option to allow short exception handling clauses on
514 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000515 // FIXME: This isn't covered by tests.
516 // FIXME: For catch, __except, __finally the first token on the line
517 // is '}', so this isn't correct here.
518 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
519 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000520 return 0;
521 }
522
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000523 if (Line.Last->is(tok::l_brace)) {
524 FormatToken *Tok = I[1]->First;
525 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
526 (Tok->getNextNonComment() == nullptr ||
527 Tok->getNextNonComment()->is(tok::semi))) {
528 // We merge empty blocks even if the line exceeds the column limit.
529 Tok->SpacesRequiredBefore = 0;
530 Tok->CanBreakBefore = true;
531 return 1;
532 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
533 !startsExternCBlock(Line)) {
534 // We don't merge short records.
Martin Probstc160cfa2017-11-25 09:35:33 +0000535 FormatToken *RecordTok = Line.First;
536 // Skip record modifiers.
537 while (RecordTok->Next &&
538 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
539 Keywords.kw_declare, Keywords.kw_abstract,
540 tok::kw_default))
541 RecordTok = RecordTok->Next;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000542 if (RecordTok &&
543 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
544 Keywords.kw_interface))
545 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000546
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000547 // Check that we still have three lines and they fit into the limit.
548 if (I + 2 == E || I[2]->Type == LT_Invalid)
549 return 0;
550 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper0df50932014-12-10 19:00:42 +0000551
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000552 if (!nextTwoLinesFitInto(I, Limit))
553 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000554
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000555 // Second, check that the next line does not contain any braces - if it
556 // does, readability declines when putting it into a single line.
557 if (I[1]->Last->is(TT_LineComment))
558 return 0;
559 do {
560 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
561 return 0;
562 Tok = Tok->Next;
563 } while (Tok);
564
565 // Last, check that the third line starts with a closing brace.
566 Tok = I[2]->First;
567 if (Tok->isNot(tok::r_brace))
568 return 0;
569
570 // Don't merge "if (a) { .. } else {".
571 if (Tok->Next && Tok->Next->is(tok::kw_else))
572 return 0;
573
574 return 2;
575 }
576 } else if (I[1]->First->is(tok::l_brace)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000577 if (I[1]->Last->is(TT_LineComment))
578 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000579
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000580 // Check for Limit <= 2 to account for the " {".
581 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000582 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000583 Limit -= 2;
584 unsigned MergedLines = 0;
585 if (Style.AllowShortBlocksOnASingleLine ||
586 (I[1]->First == I[1]->Last && I + 2 != E &&
587 I[2]->First->is(tok::r_brace))) {
588 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
589 // If we managed to merge the block, count the statement header, which
590 // is on a separate line.
591 if (MergedLines > 0)
592 ++MergedLines;
593 }
594 return MergedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000595 }
596 return 0;
597 }
598
599 /// Returns the modified column limit for \p I if it is inside a macro and
600 /// needs a trailing '\'.
601 unsigned
602 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
603 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
604 unsigned Limit) {
605 if (I[0]->InPPDirective && I + 1 != E &&
606 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
607 return Limit < 2 ? 0 : Limit - 2;
608 }
609 return Limit;
610 }
611
612 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
613 unsigned Limit) {
614 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
615 return false;
616 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
617 }
618
619 bool containsMustBreak(const AnnotatedLine *Line) {
620 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
621 if (Tok->MustBreakBefore)
622 return true;
623 }
624 return false;
625 }
626
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000627 void join(AnnotatedLine &A, const AnnotatedLine &B) {
628 assert(!A.Last->Next);
629 assert(!B.First->Previous);
630 if (B.Affected)
631 A.Affected = true;
632 A.Last->Next = B.First;
633 B.First->Previous = A.Last;
634 B.First->CanBreakBefore = true;
635 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
636 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
637 Tok->TotalLength += LengthA;
638 A.Last = Tok;
639 }
640 }
641
Daniel Jasper0df50932014-12-10 19:00:42 +0000642 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000643 const AdditionalKeywords &Keywords;
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000644 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000645
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000646 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
Francois Ferrande56a8292017-06-14 12:29:47 +0000647 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000648};
649
Daniel Jasperd1c13732015-01-23 19:37:25 +0000650static void markFinalized(FormatToken *Tok) {
651 for (; Tok; Tok = Tok->Next) {
652 Tok->Finalized = true;
653 for (AnnotatedLine *Child : Tok->Children)
654 markFinalized(Child->First);
655 }
656}
657
Manuel Klimekd3585db2015-05-11 08:21:35 +0000658#ifndef NDEBUG
659static void printLineState(const LineState &State) {
660 llvm::dbgs() << "State: ";
661 for (const ParenState &P : State.Stack) {
Krasimir Georgiev8b4bc76a232018-05-09 09:02:11 +0000662 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
663 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
Manuel Klimekd3585db2015-05-11 08:21:35 +0000664 }
665 llvm::dbgs() << State.NextToken->TokenText << "\n";
666}
667#endif
668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000669/// Base class for classes that format one \c AnnotatedLine.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000670class LineFormatter {
671public:
672 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
673 const FormatStyle &Style,
674 UnwrappedLineFormatter *BlockFormatter)
675 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
676 BlockFormatter(BlockFormatter) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000677 virtual ~LineFormatter() {}
Manuel Klimekd3585db2015-05-11 08:21:35 +0000678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000679 /// Formats an \c AnnotatedLine and returns the penalty.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000680 ///
681 /// If \p DryRun is \c false, directly applies the changes.
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000682 virtual unsigned formatLine(const AnnotatedLine &Line,
683 unsigned FirstIndent,
684 unsigned FirstStartColumn,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000685 bool DryRun) = 0;
686
687protected:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000688 /// If the \p State's next token is an r_brace closing a nested block,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000689 /// format the nested block before it.
690 ///
691 /// Returns \c true if all children could be placed successfully and adapts
692 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
693 /// creates changes using \c Whitespaces.
694 ///
695 /// The crucial idea here is that children always get formatted upon
696 /// encountering the closing brace right after the nested block. Now, if we
697 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
698 /// \c false), the entire block has to be kept on the same line (which is only
699 /// possible if it fits on the line, only contains a single statement, etc.
700 ///
701 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
702 /// break after the "{", format all lines with correct indentation and the put
703 /// the closing "}" on yet another new line.
704 ///
705 /// This enables us to keep the simple structure of the
706 /// \c UnwrappedLineFormatter, where we only have two options for each token:
707 /// break or don't break.
708 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
709 unsigned &Penalty) {
710 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
711 FormatToken &Previous = *State.NextToken->Previous;
712 if (!LBrace || LBrace->isNot(tok::l_brace) ||
713 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
714 // The previous token does not open a block. Nothing to do. We don't
715 // assert so that we can simply call this function for all tokens.
716 return true;
717
718 if (NewLine) {
719 int AdditionalIndent = State.Stack.back().Indent -
720 Previous.Children[0]->Level * Style.IndentWidth;
721
722 Penalty +=
723 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
724 /*FixBadIndentation=*/true);
725 return true;
726 }
727
728 if (Previous.Children[0]->First->MustBreakBefore)
729 return false;
730
Manuel Klimekd3585db2015-05-11 08:21:35 +0000731 // Cannot merge into one line if this line ends on a comment.
732 if (Previous.is(tok::comment))
733 return false;
734
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000735 // Cannot merge multiple statements into a single line.
736 if (Previous.Children.size() > 1)
737 return false;
738
739 const AnnotatedLine *Child = Previous.Children[0];
Manuel Klimekd3585db2015-05-11 08:21:35 +0000740 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000741 if (Child->Last->isTrailingComment())
Manuel Klimekd3585db2015-05-11 08:21:35 +0000742 return false;
743
744 // If the child line exceeds the column limit, we wouldn't want to merge it.
745 // We add +2 for the trailing " }".
746 if (Style.ColumnLimit > 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000747 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000748 return false;
749
750 if (!DryRun) {
751 Whitespaces->replaceWhitespace(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000752 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000753 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
754 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000755 Penalty +=
756 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000757
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000758 State.Column += 1 + Child->Last->TotalLength;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000759 return true;
760 }
761
762 ContinuationIndenter *Indenter;
763
764private:
765 WhitespaceManager *Whitespaces;
766 const FormatStyle &Style;
767 UnwrappedLineFormatter *BlockFormatter;
768};
769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000770/// Formatter that keeps the existing line breaks.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000771class NoColumnLimitLineFormatter : public LineFormatter {
772public:
773 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
774 WhitespaceManager *Whitespaces,
775 const FormatStyle &Style,
776 UnwrappedLineFormatter *BlockFormatter)
777 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000779 /// Formats the line, simply keeping all of the input's line breaking
Manuel Klimekd3585db2015-05-11 08:21:35 +0000780 /// decisions.
781 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000782 unsigned FirstStartColumn, bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000783 assert(!DryRun);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000784 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
785 &Line, /*DryRun=*/false);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000786 while (State.NextToken) {
787 bool Newline =
788 Indenter->mustBreak(State) ||
789 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
790 unsigned Penalty = 0;
791 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
792 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
793 }
794 return 0;
795 }
796};
797
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000798/// Formatter that puts all tokens into a single line without breaks.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000799class NoLineBreakFormatter : public LineFormatter {
800public:
801 NoLineBreakFormatter(ContinuationIndenter *Indenter,
802 WhitespaceManager *Whitespaces, const FormatStyle &Style,
803 UnwrappedLineFormatter *BlockFormatter)
804 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
805
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000806 /// Puts all tokens into a single line.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000807 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000808 unsigned FirstStartColumn, bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000809 unsigned Penalty = 0;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000810 LineState State =
811 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000812 while (State.NextToken) {
813 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
Krasimir Georgiev994b6c92017-05-18 08:07:52 +0000814 Indenter->addTokenToState(
815 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000816 }
817 return Penalty;
818 }
819};
820
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000821/// Finds the best way to break lines.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000822class OptimizingLineFormatter : public LineFormatter {
823public:
824 OptimizingLineFormatter(ContinuationIndenter *Indenter,
825 WhitespaceManager *Whitespaces,
826 const FormatStyle &Style,
827 UnwrappedLineFormatter *BlockFormatter)
828 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
829
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000830 /// Formats the line by finding the best line breaks with line lengths
Manuel Klimekd3585db2015-05-11 08:21:35 +0000831 /// below the column limit.
832 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000833 unsigned FirstStartColumn, bool DryRun) override {
834 LineState State =
835 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000836
837 // If the ObjC method declaration does not fit on a line, we should format
838 // it with one arg per line.
839 if (State.Line->Type == LT_ObjCMethodDecl)
840 State.Stack.back().BreakBeforeParameter = true;
841
842 // Find best solution in solution space.
843 return analyzeSolutionSpace(State, DryRun);
844 }
845
846private:
847 struct CompareLineStatePointers {
848 bool operator()(LineState *obj1, LineState *obj2) const {
849 return *obj1 < *obj2;
850 }
851 };
852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000853 /// A pair of <penalty, count> that is used to prioritize the BFS on.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000854 ///
855 /// In case of equal penalties, we want to prefer states that were inserted
856 /// first. During state generation we make sure that we insert states first
857 /// that break the line as late as possible.
858 typedef std::pair<unsigned, unsigned> OrderedPenalty;
859
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000860 /// An edge in the solution space from \c Previous->State to \c State,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000861 /// inserting a newline dependent on the \c NewLine.
862 struct StateNode {
863 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
864 : State(State), NewLine(NewLine), Previous(Previous) {}
865 LineState State;
866 bool NewLine;
867 StateNode *Previous;
868 };
869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000870 /// An item in the prioritized BFS search queue. The \c StateNode's
Manuel Klimekd3585db2015-05-11 08:21:35 +0000871 /// \c State has the given \c OrderedPenalty.
872 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000874 /// The BFS queue type.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000875 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
Manuel Klimek89628f62017-09-20 09:51:03 +0000876 std::greater<QueueItem>>
877 QueueType;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000879 /// Analyze the entire solution space starting from \p InitialState.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000880 ///
881 /// This implements a variant of Dijkstra's algorithm on the graph that spans
882 /// the solution space (\c LineStates are the nodes). The algorithm tries to
883 /// find the shortest path (the one with lowest penalty) from \p InitialState
884 /// to a state where all tokens are placed. Returns the penalty.
885 ///
886 /// If \p DryRun is \c false, directly applies the changes.
887 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
888 std::set<LineState *, CompareLineStatePointers> Seen;
889
890 // Increasing count of \c StateNode items we have created. This is used to
891 // create a deterministic order independent of the container.
892 unsigned Count = 0;
893 QueueType Queue;
894
895 // Insert start element into queue.
896 StateNode *Node =
897 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
898 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
899 ++Count;
900
901 unsigned Penalty = 0;
902
903 // While not empty, take first element and follow edges.
904 while (!Queue.empty()) {
905 Penalty = Queue.top().first.first;
906 StateNode *Node = Queue.top().second;
907 if (!Node->State.NextToken) {
908 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
909 break;
910 }
911 Queue.pop();
912
913 // Cut off the analysis of certain solutions if the analysis gets too
914 // complex. See description of IgnoreStackForComparison.
Daniel Jasper75bf2032015-10-27 22:55:55 +0000915 if (Count > 50000)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000916 Node->State.IgnoreStackForComparison = true;
917
918 if (!Seen.insert(&Node->State).second)
919 // State already examined with lower penalty.
920 continue;
921
922 FormatDecision LastFormat = Node->State.NextToken->Decision;
923 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
924 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
925 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
926 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
927 }
928
929 if (Queue.empty()) {
930 // We were unable to find a solution, do nothing.
931 // FIXME: Add diagnostic?
932 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
933 return 0;
934 }
935
936 // Reconstruct the solution.
937 if (!DryRun)
938 reconstructPath(InitialState, Queue.top().second);
939
940 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
941 DEBUG(llvm::dbgs() << "---\n");
942
943 return Penalty;
944 }
945
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000946 /// Add the following state to the analysis queue \c Queue.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000947 ///
948 /// Assume the current state is \p PreviousNode and has been reached with a
949 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
950 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
951 bool NewLine, unsigned *Count, QueueType *Queue) {
952 if (NewLine && !Indenter->canBreak(PreviousNode->State))
953 return;
954 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
955 return;
956
957 StateNode *Node = new (Allocator.Allocate())
958 StateNode(PreviousNode->State, NewLine, PreviousNode);
959 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
960 return;
961
962 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
963
964 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
965 ++(*Count);
966 }
967
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000968 /// Applies the best formatting by reconstructing the path in the
Manuel Klimekd3585db2015-05-11 08:21:35 +0000969 /// solution space that leads to \c Best.
970 void reconstructPath(LineState &State, StateNode *Best) {
971 std::deque<StateNode *> Path;
972 // We do not need a break before the initial token.
973 while (Best->Previous) {
974 Path.push_front(Best);
975 Best = Best->Previous;
976 }
977 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
978 I != E; ++I) {
979 unsigned Penalty = 0;
980 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
981 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
982
983 DEBUG({
984 printLineState((*I)->Previous->State);
985 if ((*I)->NewLine) {
986 llvm::dbgs() << "Penalty for placing "
987 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
988 << Penalty << "\n";
989 }
990 });
991 }
992 }
993
994 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
995};
996
Hans Wennborg7eb54642015-09-10 17:07:54 +0000997} // anonymous namespace
Daniel Jasper0df50932014-12-10 19:00:42 +0000998
999unsigned
1000UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
1001 bool DryRun, int AdditionalIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001002 bool FixBadIndentation,
1003 unsigned FirstStartColumn,
1004 unsigned NextStartColumn,
1005 unsigned LastStartColumn) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001006 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +00001007
1008 // Try to look up already computed penalty in DryRun-mode.
1009 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1010 &Lines, AdditionalIndent);
1011 auto CacheIt = PenaltyCache.find(CacheKey);
1012 if (DryRun && CacheIt != PenaltyCache.end())
1013 return CacheIt->second;
1014
1015 assert(!Lines.empty());
1016 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001017 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1018 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +00001019 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001020 const AnnotatedLine *NextLine = nullptr;
Daniel Jasperf67c3242015-11-01 00:27:35 +00001021
1022 // The minimum level of consecutive lines that have been formatted.
1023 unsigned RangeMinLevel = UINT_MAX;
Daniel Jasperf67c3242015-11-01 00:27:35 +00001024
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001025 bool FirstLine = true;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001026 for (const AnnotatedLine *Line =
1027 Joiner.getNextMergedLine(DryRun, IndentTracker);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001028 Line; Line = NextLine, FirstLine = false) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001029 const AnnotatedLine &TheLine = *Line;
1030 unsigned Indent = IndentTracker.getIndent();
Daniel Jasperf67c3242015-11-01 00:27:35 +00001031
1032 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1033 // scope was added. However, we need to carefully stop doing this when we
1034 // exit the scope of affected lines to prevent indenting a the entire
1035 // remaining file if it currently missing a closing brace.
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001036 bool PreviousRBrace =
1037 PreviousLine && PreviousLine->startsWith(tok::r_brace);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001038 bool ContinueFormatting =
1039 TheLine.Level > RangeMinLevel ||
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001040 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1041 !TheLine.startsWith(tok::r_brace));
Daniel Jasperf67c3242015-11-01 00:27:35 +00001042
1043 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Daniel Jaspera1036e52015-10-28 01:08:22 +00001044 Indent != TheLine.First->OriginalColumn;
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001045 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001046 // We cannot format this line; if the reason is that the line had a
1047 // parsing error, remember that.
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001048 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1049 Status->FormatComplete = false;
1050 Status->Line =
1051 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1052 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001053
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001054 if (ShouldFormat && TheLine.Type != LT_Invalid) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001055 if (!DryRun) {
1056 bool LastLine = Line->First->is(tok::eof);
Krasimir Georgiev62103052018-04-19 13:02:15 +00001057 formatFirstToken(TheLine, PreviousLine, Lines, Indent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001058 LastLine ? LastStartColumn : NextStartColumn + Indent);
1059 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001060
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001061 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1062 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1063 bool FitsIntoOneLine =
1064 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
Martin Probst0cd74ee2016-06-13 16:39:50 +00001065 (TheLine.Type == LT_ImportStatement &&
1066 (Style.Language != FormatStyle::LK_JavaScript ||
1067 !Style.JavaScriptWrapImports));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001068 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +00001069 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001070 .formatLine(TheLine, NextStartColumn + Indent,
1071 FirstLine ? FirstStartColumn : 0, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001072 else if (FitsIntoOneLine)
1073 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001074 .formatLine(TheLine, NextStartColumn + Indent,
1075 FirstLine ? FirstStartColumn : 0, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001076 else
Manuel Klimekd3585db2015-05-11 08:21:35 +00001077 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001078 .formatLine(TheLine, NextStartColumn + Indent,
1079 FirstLine ? FirstStartColumn : 0, DryRun);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001080 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
Daniel Jasper0df50932014-12-10 19:00:42 +00001081 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001082 // If no token in the current line is affected, we still need to format
1083 // affected children.
1084 if (TheLine.ChildrenAffected)
Daniel Jasper35ca66d2016-02-29 12:26:20 +00001085 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1086 if (!Tok->Children.empty())
1087 format(Tok->Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +00001088
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001089 // Adapt following lines on the current indent level to the same level
1090 // unless the current \c AnnotatedLine is not at the beginning of a line.
1091 bool StartsNewLine =
1092 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1093 if (StartsNewLine)
1094 IndentTracker.adjustToUnmodifiedLine(TheLine);
1095 if (!DryRun) {
1096 bool ReformatLeadingWhitespace =
1097 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1098 TheLine.LeadingEmptyLinesAffected);
1099 // Format the first token.
1100 if (ReformatLeadingWhitespace)
Krasimir Georgiev62103052018-04-19 13:02:15 +00001101 formatFirstToken(TheLine, PreviousLine, Lines,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001102 TheLine.First->OriginalColumn,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001103 TheLine.First->OriginalColumn);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001104 else
1105 Whitespaces->addUntouchableToken(*TheLine.First,
1106 TheLine.InPPDirective);
1107
1108 // Notify the WhitespaceManager about the unchanged whitespace.
1109 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +00001110 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +00001111 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001112 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001113 RangeMinLevel = UINT_MAX;
Daniel Jasper0df50932014-12-10 19:00:42 +00001114 }
Daniel Jasperd1c13732015-01-23 19:37:25 +00001115 if (!DryRun)
1116 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001117 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +00001118 }
1119 PenaltyCache[CacheKey] = Penalty;
1120 return Penalty;
1121}
1122
Krasimir Georgiev62103052018-04-19 13:02:15 +00001123void UnwrappedLineFormatter::formatFirstToken(
1124 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1125 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1126 unsigned NewlineIndent) {
Manuel Klimek89628f62017-09-20 09:51:03 +00001127 FormatToken &RootToken = *Line.First;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001128 if (RootToken.is(tok::eof)) {
1129 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001130 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1131 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1132 TokenIndent);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001133 return;
1134 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001135 unsigned Newlines =
1136 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1137 // Remove empty lines before "}" where applicable.
1138 if (RootToken.is(tok::r_brace) &&
1139 (!RootToken.Next ||
Krasimir Georgiev62103052018-04-19 13:02:15 +00001140 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1141 // Do not remove empty lines before namespace closing "}".
1142 !getNamespaceToken(&Line, Lines))
Daniel Jasper0df50932014-12-10 19:00:42 +00001143 Newlines = std::min(Newlines, 1u);
Martin Probsta004b3f2017-11-17 18:06:33 +00001144 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1145 if (PreviousLine == nullptr && Line.Level > 0)
1146 Newlines = std::min(Newlines, 1u);
Daniel Jasper0df50932014-12-10 19:00:42 +00001147 if (Newlines == 0 && !RootToken.IsFirst)
1148 Newlines = 1;
1149 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1150 Newlines = 0;
1151
1152 // Remove empty lines after "{".
1153 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1154 PreviousLine->Last->is(tok::l_brace) &&
1155 PreviousLine->First->isNot(tok::kw_namespace) &&
1156 !startsExternCBlock(*PreviousLine))
1157 Newlines = 1;
1158
1159 // Insert extra new line before access specifiers.
1160 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1161 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1162 ++Newlines;
1163
1164 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +00001165 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1166 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +00001167 Newlines = std::min(1u, Newlines);
1168
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001169 if (Newlines)
1170 Indent = NewlineIndent;
1171
1172 // Preprocessor directives get indented after the hash, if indented.
1173 if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement)
1174 Indent = 0;
1175
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001176 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1177 Line.InPPDirective &&
1178 !RootToken.HasUnescapedNewline);
Daniel Jasper0df50932014-12-10 19:00:42 +00001179}
1180
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001181unsigned
1182UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1183 const AnnotatedLine *NextLine) const {
1184 // In preprocessor directives reserve two chars for trailing " \" if the
1185 // next line continues the preprocessor directive.
1186 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +00001187 InPPDirective &&
1188 // If there is no next line, this is likely a child line and the parent
1189 // continues the preprocessor directive.
1190 (!NextLine ||
1191 (NextLine->InPPDirective &&
1192 // If there is an unescaped newline between this line and the next, the
1193 // next line starts a new preprocessor directive.
1194 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001195 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +00001196}
1197
Daniel Jasper0df50932014-12-10 19:00:42 +00001198} // namespace format
1199} // namespace clang