blob: f14e3851c8de22b6c0b881fc6a73245bc0110a6b [file] [log] [blame]
Daniel Jasper0df50932014-12-10 19:00:42 +00001//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Jasper0df50932014-12-10 19:00:42 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "UnwrappedLineFormatter.h"
Paul Hoad5bcf99b2019-03-01 09:09:54 +000010#include "NamespaceEndCommentsFixer.h"
Daniel Jasper0df50932014-12-10 19:00:42 +000011#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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000029/// Tracks the indent level of \c AnnotatedLines across levels.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000030///
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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048 /// Returns the indent for the current line.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000049 unsigned getIndent() const { return Indent; }
50
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051 /// Update the indent state given that \p Line is going to be formatted
Manuel Klimek3d3ea842015-05-12 09:23:57 +000052 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000069 /// Update the indent state given that \p Line indent should be
Francois Ferrande56a8292017-06-14 12:29:47 +000070 /// skipped.
71 void skipLine(const AnnotatedLine &Line) {
72 while (IndentForLevel.size() <= Line.Level)
73 IndentForLevel.push_back(Indent);
74 }
75
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000076 /// Update the level indent to adapt to the given \p Line.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000077 ///
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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000091 /// Get the offset of the line relatively to the level.
Manuel Klimek3d3ea842015-05-12 09:23:57 +000092 ///
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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000107 /// Get the indent of \p Level from \p IndentForLevel.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000108 ///
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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000124 /// The indent in characters for each level.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000125 std::vector<int> IndentForLevel;
126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000127 /// Offset of the current line relative to the indent level.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000128 ///
129 /// For example, the 'public' keywords is often indented with a negative
130 /// offset.
131 int Offset = 0;
132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000133 /// The current line's indent.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000134 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000160 /// Returns the next line, merging multiple lines into one if possible.
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000161 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000182 /// Calculates how many lines can be merged into 1 starting at \p I.
Daniel Jasper0df50932014-12-10 19:00:42 +0000183 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;
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000254 unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
Francois Ferrande56a8292017-06-14 12:29:47 +0000255 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000256 closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
Francois Ferrande56a8292017-06-14 12:29:47 +0000257 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 }
Francois Ferranda2484b22018-02-27 13:48:27 +0000317 // Don't merge block with left brace wrapped after ObjC special blocks
318 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
319 I[-1]->First->is(tok::at) && I[-1]->First->Next) {
320 tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
321 if (kwId == clang::tok::objc_autoreleasepool ||
322 kwId == clang::tok::objc_synchronized)
323 return 0;
324 }
Owen Pan58c3dee2018-09-13 07:27:15 +0000325 // Don't merge block with left brace wrapped after case labels
326 if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
327 I[-1]->First->isOneOf(tok::kw_case, tok::kw_default))
328 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000329 // Try to merge a block with left brace wrapped that wasn't yet covered
330 if (TheLine->Last->is(tok::l_brace)) {
331 return !Style.BraceWrapping.AfterFunction ||
Manuel Klimek89628f62017-09-20 09:51:03 +0000332 (I[1]->First->is(tok::r_brace) &&
333 !Style.BraceWrapping.SplitEmptyRecord)
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000334 ? tryMergeSimpleBlock(I, E, Limit)
335 : 0;
336 }
337 // Try to merge a function block with left brace wrapped
Daniel Jasper0df50932014-12-10 19:00:42 +0000338 if (I[1]->First->is(TT_FunctionLBrace) &&
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000339 Style.BraceWrapping.AfterFunction) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000340 if (I[1]->Last->is(TT_LineComment))
341 return 0;
342
343 // Check for Limit <= 2 to account for the " {".
344 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
345 return 0;
346 Limit -= 2;
347
348 unsigned MergedLines = 0;
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000349 if (MergeShortFunctions ||
350 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
351 I[1]->First == I[1]->Last && I + 2 != E &&
352 I[2]->First->is(tok::r_brace))) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000353 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
354 // If we managed to merge the block, count the function header, which is
355 // on a separate line.
356 if (MergedLines > 0)
357 ++MergedLines;
358 }
359 return MergedLines;
360 }
361 if (TheLine->First->is(tok::kw_if)) {
362 return Style.AllowShortIfStatementsOnASingleLine
363 ? tryMergeSimpleControlStatement(I, E, Limit)
364 : 0;
365 }
366 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
367 return Style.AllowShortLoopsOnASingleLine
368 ? tryMergeSimpleControlStatement(I, E, Limit)
369 : 0;
370 }
371 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
372 return Style.AllowShortCaseLabelsOnASingleLine
373 ? tryMergeShortCaseLabels(I, E, Limit)
374 : 0;
375 }
376 if (TheLine->InPPDirective &&
377 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
378 return tryMergeSimplePPDirective(I, E, Limit);
379 }
380 return 0;
381 }
382
Daniel Jasper0df50932014-12-10 19:00:42 +0000383 unsigned
384 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
385 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
386 unsigned Limit) {
387 if (Limit == 0)
388 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000389 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
390 return 0;
391 if (1 + I[1]->Last->TotalLength > Limit)
392 return 0;
393 return 1;
394 }
395
396 unsigned tryMergeSimpleControlStatement(
397 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
398 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
399 if (Limit == 0)
400 return 0;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000401 if (Style.BraceWrapping.AfterControlStatement &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000402 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
403 return 0;
404 if (I[1]->InPPDirective != (*I)->InPPDirective ||
405 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
406 return 0;
407 Limit = limitConsideringMacros(I + 1, E, Limit);
408 AnnotatedLine &Line = **I;
409 if (Line.Last->isNot(tok::r_paren))
410 return 0;
411 if (1 + I[1]->Last->TotalLength > Limit)
412 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000413 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
414 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000415 return 0;
Paul Hoad15000a12019-03-13 08:26:39 +0000416 // Only inline simple if's (no nested if or else), unless specified
417 if (Style.AllowShortIfStatementsOnASingleLine != FormatStyle::SIS_Always) {
418 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
419 I[2]->First->is(tok::kw_else))
420 return 0;
421 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000422 return 1;
423 }
424
Manuel Klimekd3585db2015-05-11 08:21:35 +0000425 unsigned
426 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
427 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
428 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000429 if (Limit == 0 || I + 1 == E ||
430 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
431 return 0;
Owen Pan9da65a32018-09-21 03:46:36 +0000432 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
433 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000434 unsigned NumStmts = 0;
435 unsigned Length = 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000436 bool EndsWithComment = false;
Daniel Jasper0df50932014-12-10 19:00:42 +0000437 bool InPPDirective = I[0]->InPPDirective;
Francois Ferranda64ba702017-07-28 07:56:18 +0000438 const unsigned Level = I[0]->Level;
Daniel Jasper0df50932014-12-10 19:00:42 +0000439 for (; NumStmts < 3; ++NumStmts) {
440 if (I + 1 + NumStmts == E)
441 break;
442 const AnnotatedLine *Line = I[1 + NumStmts];
443 if (Line->InPPDirective != InPPDirective)
444 break;
445 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
446 break;
447 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Francois Ferranda64ba702017-07-28 07:56:18 +0000448 tok::kw_while) ||
449 EndsWithComment)
Daniel Jasper0df50932014-12-10 19:00:42 +0000450 return 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000451 if (Line->First->is(tok::comment)) {
452 if (Level != Line->Level)
453 return 0;
454 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
455 for (; J != E; ++J) {
456 Line = *J;
457 if (Line->InPPDirective != InPPDirective)
458 break;
459 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
460 break;
461 if (Line->First->isNot(tok::comment) || Level != Line->Level)
462 return 0;
463 }
464 break;
465 }
466 if (Line->Last->is(tok::comment))
467 EndsWithComment = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000468 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
469 }
470 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
471 return 0;
472 return NumStmts;
473 }
474
475 unsigned
476 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
477 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
478 unsigned Limit) {
479 AnnotatedLine &Line = **I;
480
481 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000482 // FIXME: If an option to allow short exception handling clauses on a single
483 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000484 if (Style.Language != FormatStyle::LK_Java &&
485 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
486 return 0;
487
488 // Check that the current line allows merging. This depends on whether we
489 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000490 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
Krasimir Georgiev6a1c9d52017-10-02 15:53:37 +0000491 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000492 return 0;
Jonas Toth81b61a82018-09-02 09:04:51 +0000493 // default: in switch statement
494 if (Line.First->is(tok::kw_default)) {
495 const FormatToken *Tok = Line.First->getNextNonComment();
496 if (Tok && Tok->is(tok::colon))
497 return 0;
498 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000499 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000500 tok::kw___try, tok::kw_catch, tok::kw___finally,
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000501 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000502 if (!Style.AllowShortBlocksOnASingleLine)
503 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000504 // Don't merge when we can't except the case when
505 // the control statement block is empty
Daniel Jasper0df50932014-12-10 19:00:42 +0000506 if (!Style.AllowShortIfStatementsOnASingleLine &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000507 Line.startsWith(tok::kw_if) &&
508 !Style.BraceWrapping.AfterControlStatement &&
509 !I[1]->First->is(tok::r_brace))
510 return 0;
511 if (!Style.AllowShortIfStatementsOnASingleLine &&
512 Line.startsWith(tok::kw_if) &&
513 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
514 !I[2]->First->is(tok::r_brace))
Daniel Jasper0df50932014-12-10 19:00:42 +0000515 return 0;
516 if (!Style.AllowShortLoopsOnASingleLine &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000517 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
518 !Style.BraceWrapping.AfterControlStatement &&
519 !I[1]->First->is(tok::r_brace))
520 return 0;
521 if (!Style.AllowShortLoopsOnASingleLine &&
522 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
523 Style.BraceWrapping.AfterControlStatement && I + 2 != E &&
524 !I[2]->First->is(tok::r_brace))
Daniel Jasper0df50932014-12-10 19:00:42 +0000525 return 0;
526 // FIXME: Consider an option to allow short exception handling clauses on
527 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000528 // FIXME: This isn't covered by tests.
529 // FIXME: For catch, __except, __finally the first token on the line
530 // is '}', so this isn't correct here.
531 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
532 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000533 return 0;
534 }
535
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000536 if (Line.Last->is(tok::l_brace)) {
537 FormatToken *Tok = I[1]->First;
538 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
539 (Tok->getNextNonComment() == nullptr ||
540 Tok->getNextNonComment()->is(tok::semi))) {
541 // We merge empty blocks even if the line exceeds the column limit.
542 Tok->SpacesRequiredBefore = 0;
543 Tok->CanBreakBefore = true;
544 return 1;
Sam McCall6f3778c2018-09-05 07:44:02 +0000545 } else if (Limit != 0 && !Line.startsWithNamespace() &&
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000546 !startsExternCBlock(Line)) {
547 // We don't merge short records.
Martin Probstc160cfa2017-11-25 09:35:33 +0000548 FormatToken *RecordTok = Line.First;
549 // Skip record modifiers.
550 while (RecordTok->Next &&
551 RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
552 Keywords.kw_declare, Keywords.kw_abstract,
553 tok::kw_default))
554 RecordTok = RecordTok->Next;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000555 if (RecordTok &&
556 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
557 Keywords.kw_interface))
558 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000559
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000560 // Check that we still have three lines and they fit into the limit.
561 if (I + 2 == E || I[2]->Type == LT_Invalid)
562 return 0;
563 Limit = limitConsideringMacros(I + 2, E, Limit);
Daniel Jasper0df50932014-12-10 19:00:42 +0000564
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000565 if (!nextTwoLinesFitInto(I, Limit))
566 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000567
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000568 // Second, check that the next line does not contain any braces - if it
569 // does, readability declines when putting it into a single line.
570 if (I[1]->Last->is(TT_LineComment))
571 return 0;
572 do {
573 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
574 return 0;
575 Tok = Tok->Next;
576 } while (Tok);
577
578 // Last, check that the third line starts with a closing brace.
579 Tok = I[2]->First;
580 if (Tok->isNot(tok::r_brace))
581 return 0;
582
583 // Don't merge "if (a) { .. } else {".
584 if (Tok->Next && Tok->Next->is(tok::kw_else))
585 return 0;
586
587 return 2;
588 }
589 } else if (I[1]->First->is(tok::l_brace)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000590 if (I[1]->Last->is(TT_LineComment))
591 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000592
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000593 // Check for Limit <= 2 to account for the " {".
594 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000595 return 0;
Krasimir Georgiev3b0b50b2017-09-11 10:12:16 +0000596 Limit -= 2;
597 unsigned MergedLines = 0;
598 if (Style.AllowShortBlocksOnASingleLine ||
599 (I[1]->First == I[1]->Last && I + 2 != E &&
600 I[2]->First->is(tok::r_brace))) {
601 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
602 // If we managed to merge the block, count the statement header, which
603 // is on a separate line.
604 if (MergedLines > 0)
605 ++MergedLines;
606 }
607 return MergedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000608 }
609 return 0;
610 }
611
612 /// Returns the modified column limit for \p I if it is inside a macro and
613 /// needs a trailing '\'.
614 unsigned
615 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
616 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
617 unsigned Limit) {
618 if (I[0]->InPPDirective && I + 1 != E &&
619 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
620 return Limit < 2 ? 0 : Limit - 2;
621 }
622 return Limit;
623 }
624
625 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
626 unsigned Limit) {
627 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
628 return false;
629 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
630 }
631
632 bool containsMustBreak(const AnnotatedLine *Line) {
633 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
634 if (Tok->MustBreakBefore)
635 return true;
636 }
637 return false;
638 }
639
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000640 void join(AnnotatedLine &A, const AnnotatedLine &B) {
641 assert(!A.Last->Next);
642 assert(!B.First->Previous);
643 if (B.Affected)
644 A.Affected = true;
645 A.Last->Next = B.First;
646 B.First->Previous = A.Last;
647 B.First->CanBreakBefore = true;
648 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
649 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
650 Tok->TotalLength += LengthA;
651 A.Last = Tok;
652 }
653 }
654
Daniel Jasper0df50932014-12-10 19:00:42 +0000655 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000656 const AdditionalKeywords &Keywords;
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000657 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000658
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000659 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
Francois Ferrande56a8292017-06-14 12:29:47 +0000660 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000661};
662
Daniel Jasperd1c13732015-01-23 19:37:25 +0000663static void markFinalized(FormatToken *Tok) {
664 for (; Tok; Tok = Tok->Next) {
665 Tok->Finalized = true;
666 for (AnnotatedLine *Child : Tok->Children)
667 markFinalized(Child->First);
668 }
669}
670
Manuel Klimekd3585db2015-05-11 08:21:35 +0000671#ifndef NDEBUG
672static void printLineState(const LineState &State) {
673 llvm::dbgs() << "State: ";
674 for (const ParenState &P : State.Stack) {
Krasimir Georgiev8b4bc76a232018-05-09 09:02:11 +0000675 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
676 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
Manuel Klimekd3585db2015-05-11 08:21:35 +0000677 }
678 llvm::dbgs() << State.NextToken->TokenText << "\n";
679}
680#endif
681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000682/// Base class for classes that format one \c AnnotatedLine.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000683class LineFormatter {
684public:
685 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
686 const FormatStyle &Style,
687 UnwrappedLineFormatter *BlockFormatter)
688 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
689 BlockFormatter(BlockFormatter) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000690 virtual ~LineFormatter() {}
Manuel Klimekd3585db2015-05-11 08:21:35 +0000691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000692 /// Formats an \c AnnotatedLine and returns the penalty.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000693 ///
694 /// If \p DryRun is \c false, directly applies the changes.
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000695 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
696 unsigned FirstStartColumn, bool DryRun) = 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000697
698protected:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000699 /// If the \p State's next token is an r_brace closing a nested block,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000700 /// format the nested block before it.
701 ///
702 /// Returns \c true if all children could be placed successfully and adapts
703 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
704 /// creates changes using \c Whitespaces.
705 ///
706 /// The crucial idea here is that children always get formatted upon
707 /// encountering the closing brace right after the nested block. Now, if we
708 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
709 /// \c false), the entire block has to be kept on the same line (which is only
710 /// possible if it fits on the line, only contains a single statement, etc.
711 ///
712 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
713 /// break after the "{", format all lines with correct indentation and the put
714 /// the closing "}" on yet another new line.
715 ///
716 /// This enables us to keep the simple structure of the
717 /// \c UnwrappedLineFormatter, where we only have two options for each token:
718 /// break or don't break.
719 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
720 unsigned &Penalty) {
721 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
722 FormatToken &Previous = *State.NextToken->Previous;
723 if (!LBrace || LBrace->isNot(tok::l_brace) ||
724 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
725 // The previous token does not open a block. Nothing to do. We don't
726 // assert so that we can simply call this function for all tokens.
727 return true;
728
729 if (NewLine) {
730 int AdditionalIndent = State.Stack.back().Indent -
731 Previous.Children[0]->Level * Style.IndentWidth;
732
733 Penalty +=
734 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
735 /*FixBadIndentation=*/true);
736 return true;
737 }
738
739 if (Previous.Children[0]->First->MustBreakBefore)
740 return false;
741
Manuel Klimekd3585db2015-05-11 08:21:35 +0000742 // Cannot merge into one line if this line ends on a comment.
743 if (Previous.is(tok::comment))
744 return false;
745
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000746 // Cannot merge multiple statements into a single line.
747 if (Previous.Children.size() > 1)
748 return false;
749
750 const AnnotatedLine *Child = Previous.Children[0];
Manuel Klimekd3585db2015-05-11 08:21:35 +0000751 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000752 if (Child->Last->isTrailingComment())
Manuel Klimekd3585db2015-05-11 08:21:35 +0000753 return false;
754
755 // If the child line exceeds the column limit, we wouldn't want to merge it.
756 // We add +2 for the trailing " }".
757 if (Style.ColumnLimit > 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000758 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000759 return false;
760
761 if (!DryRun) {
762 Whitespaces->replaceWhitespace(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000763 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000764 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
765 }
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000766 Penalty +=
767 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000768
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000769 State.Column += 1 + Child->Last->TotalLength;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000770 return true;
771 }
772
773 ContinuationIndenter *Indenter;
774
775private:
776 WhitespaceManager *Whitespaces;
777 const FormatStyle &Style;
778 UnwrappedLineFormatter *BlockFormatter;
779};
780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000781/// Formatter that keeps the existing line breaks.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000782class NoColumnLimitLineFormatter : public LineFormatter {
783public:
784 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
785 WhitespaceManager *Whitespaces,
786 const FormatStyle &Style,
787 UnwrappedLineFormatter *BlockFormatter)
788 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
789
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000790 /// Formats the line, simply keeping all of the input's line breaking
Manuel Klimekd3585db2015-05-11 08:21:35 +0000791 /// decisions.
792 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000793 unsigned FirstStartColumn, bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000794 assert(!DryRun);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000795 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
796 &Line, /*DryRun=*/false);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000797 while (State.NextToken) {
798 bool Newline =
799 Indenter->mustBreak(State) ||
800 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
801 unsigned Penalty = 0;
802 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
803 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
804 }
805 return 0;
806 }
807};
808
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000809/// Formatter that puts all tokens into a single line without breaks.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000810class NoLineBreakFormatter : public LineFormatter {
811public:
812 NoLineBreakFormatter(ContinuationIndenter *Indenter,
813 WhitespaceManager *Whitespaces, const FormatStyle &Style,
814 UnwrappedLineFormatter *BlockFormatter)
815 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
816
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000817 /// Puts all tokens into a single line.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000818 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000819 unsigned FirstStartColumn, bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000820 unsigned Penalty = 0;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000821 LineState State =
822 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000823 while (State.NextToken) {
824 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
Krasimir Georgiev994b6c92017-05-18 08:07:52 +0000825 Indenter->addTokenToState(
826 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000827 }
828 return Penalty;
829 }
830};
831
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000832/// Finds the best way to break lines.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000833class OptimizingLineFormatter : public LineFormatter {
834public:
835 OptimizingLineFormatter(ContinuationIndenter *Indenter,
836 WhitespaceManager *Whitespaces,
837 const FormatStyle &Style,
838 UnwrappedLineFormatter *BlockFormatter)
839 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
840
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000841 /// Formats the line by finding the best line breaks with line lengths
Manuel Klimekd3585db2015-05-11 08:21:35 +0000842 /// below the column limit.
843 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000844 unsigned FirstStartColumn, bool DryRun) override {
845 LineState State =
846 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000847
848 // If the ObjC method declaration does not fit on a line, we should format
849 // it with one arg per line.
850 if (State.Line->Type == LT_ObjCMethodDecl)
851 State.Stack.back().BreakBeforeParameter = true;
852
853 // Find best solution in solution space.
854 return analyzeSolutionSpace(State, DryRun);
855 }
856
857private:
858 struct CompareLineStatePointers {
859 bool operator()(LineState *obj1, LineState *obj2) const {
860 return *obj1 < *obj2;
861 }
862 };
863
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000864 /// A pair of <penalty, count> that is used to prioritize the BFS on.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000865 ///
866 /// In case of equal penalties, we want to prefer states that were inserted
867 /// first. During state generation we make sure that we insert states first
868 /// that break the line as late as possible.
869 typedef std::pair<unsigned, unsigned> OrderedPenalty;
870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000871 /// An edge in the solution space from \c Previous->State to \c State,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000872 /// inserting a newline dependent on the \c NewLine.
873 struct StateNode {
874 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
875 : State(State), NewLine(NewLine), Previous(Previous) {}
876 LineState State;
877 bool NewLine;
878 StateNode *Previous;
879 };
880
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000881 /// An item in the prioritized BFS search queue. The \c StateNode's
Manuel Klimekd3585db2015-05-11 08:21:35 +0000882 /// \c State has the given \c OrderedPenalty.
883 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
884
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000885 /// The BFS queue type.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000886 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
Manuel Klimek89628f62017-09-20 09:51:03 +0000887 std::greater<QueueItem>>
888 QueueType;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000890 /// Analyze the entire solution space starting from \p InitialState.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000891 ///
892 /// This implements a variant of Dijkstra's algorithm on the graph that spans
893 /// the solution space (\c LineStates are the nodes). The algorithm tries to
894 /// find the shortest path (the one with lowest penalty) from \p InitialState
895 /// to a state where all tokens are placed. Returns the penalty.
896 ///
897 /// If \p DryRun is \c false, directly applies the changes.
898 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
899 std::set<LineState *, CompareLineStatePointers> Seen;
900
901 // Increasing count of \c StateNode items we have created. This is used to
902 // create a deterministic order independent of the container.
903 unsigned Count = 0;
904 QueueType Queue;
905
906 // Insert start element into queue.
907 StateNode *Node =
908 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
909 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
910 ++Count;
911
912 unsigned Penalty = 0;
913
914 // While not empty, take first element and follow edges.
915 while (!Queue.empty()) {
916 Penalty = Queue.top().first.first;
917 StateNode *Node = Queue.top().second;
918 if (!Node->State.NextToken) {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000919 LLVM_DEBUG(llvm::dbgs()
920 << "\n---\nPenalty for line: " << Penalty << "\n");
Manuel Klimekd3585db2015-05-11 08:21:35 +0000921 break;
922 }
923 Queue.pop();
924
925 // Cut off the analysis of certain solutions if the analysis gets too
926 // complex. See description of IgnoreStackForComparison.
Daniel Jasper75bf2032015-10-27 22:55:55 +0000927 if (Count > 50000)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000928 Node->State.IgnoreStackForComparison = true;
929
930 if (!Seen.insert(&Node->State).second)
931 // State already examined with lower penalty.
932 continue;
933
934 FormatDecision LastFormat = Node->State.NextToken->Decision;
935 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
936 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
937 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
938 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
939 }
940
941 if (Queue.empty()) {
942 // We were unable to find a solution, do nothing.
943 // FIXME: Add diagnostic?
Nicola Zaghen3538b392018-05-15 13:30:56 +0000944 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
Manuel Klimekd3585db2015-05-11 08:21:35 +0000945 return 0;
946 }
947
948 // Reconstruct the solution.
949 if (!DryRun)
950 reconstructPath(InitialState, Queue.top().second);
951
Nicola Zaghen3538b392018-05-15 13:30:56 +0000952 LLVM_DEBUG(llvm::dbgs()
953 << "Total number of analyzed states: " << Count << "\n");
954 LLVM_DEBUG(llvm::dbgs() << "---\n");
Manuel Klimekd3585db2015-05-11 08:21:35 +0000955
956 return Penalty;
957 }
958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000959 /// Add the following state to the analysis queue \c Queue.
Manuel Klimekd3585db2015-05-11 08:21:35 +0000960 ///
961 /// Assume the current state is \p PreviousNode and has been reached with a
962 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
963 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
964 bool NewLine, unsigned *Count, QueueType *Queue) {
965 if (NewLine && !Indenter->canBreak(PreviousNode->State))
966 return;
967 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
968 return;
969
970 StateNode *Node = new (Allocator.Allocate())
971 StateNode(PreviousNode->State, NewLine, PreviousNode);
972 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
973 return;
974
975 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
976
977 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
978 ++(*Count);
979 }
980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000981 /// Applies the best formatting by reconstructing the path in the
Manuel Klimekd3585db2015-05-11 08:21:35 +0000982 /// solution space that leads to \c Best.
983 void reconstructPath(LineState &State, StateNode *Best) {
984 std::deque<StateNode *> Path;
985 // We do not need a break before the initial token.
986 while (Best->Previous) {
987 Path.push_front(Best);
988 Best = Best->Previous;
989 }
Krasimir Georgiev5528cac2018-10-31 17:56:57 +0000990 for (auto I = Path.begin(), E = Path.end(); I != E; ++I) {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000991 unsigned Penalty = 0;
992 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
993 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
994
Nicola Zaghen3538b392018-05-15 13:30:56 +0000995 LLVM_DEBUG({
Manuel Klimekd3585db2015-05-11 08:21:35 +0000996 printLineState((*I)->Previous->State);
997 if ((*I)->NewLine) {
998 llvm::dbgs() << "Penalty for placing "
Krasimir Georgiev5528cac2018-10-31 17:56:57 +0000999 << (*I)->Previous->State.NextToken->Tok.getName()
1000 << " on a new line: " << Penalty << "\n";
Manuel Klimekd3585db2015-05-11 08:21:35 +00001001 }
1002 });
1003 }
1004 }
1005
1006 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1007};
1008
Hans Wennborg7eb54642015-09-10 17:07:54 +00001009} // anonymous namespace
Daniel Jasper0df50932014-12-10 19:00:42 +00001010
Paul Hoad5bcf99b2019-03-01 09:09:54 +00001011unsigned UnwrappedLineFormatter::format(
1012 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1013 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1014 unsigned NextStartColumn, unsigned LastStartColumn) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001015 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +00001016
1017 // Try to look up already computed penalty in DryRun-mode.
1018 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1019 &Lines, AdditionalIndent);
1020 auto CacheIt = PenaltyCache.find(CacheKey);
1021 if (DryRun && CacheIt != PenaltyCache.end())
1022 return CacheIt->second;
1023
1024 assert(!Lines.empty());
1025 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001026 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1027 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +00001028 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001029 const AnnotatedLine *NextLine = nullptr;
Daniel Jasperf67c3242015-11-01 00:27:35 +00001030
1031 // The minimum level of consecutive lines that have been formatted.
1032 unsigned RangeMinLevel = UINT_MAX;
Daniel Jasperf67c3242015-11-01 00:27:35 +00001033
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001034 bool FirstLine = true;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001035 for (const AnnotatedLine *Line =
1036 Joiner.getNextMergedLine(DryRun, IndentTracker);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001037 Line; Line = NextLine, FirstLine = false) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001038 const AnnotatedLine &TheLine = *Line;
1039 unsigned Indent = IndentTracker.getIndent();
Daniel Jasperf67c3242015-11-01 00:27:35 +00001040
1041 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1042 // scope was added. However, we need to carefully stop doing this when we
1043 // exit the scope of affected lines to prevent indenting a the entire
1044 // remaining file if it currently missing a closing brace.
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001045 bool PreviousRBrace =
1046 PreviousLine && PreviousLine->startsWith(tok::r_brace);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001047 bool ContinueFormatting =
1048 TheLine.Level > RangeMinLevel ||
Manuel Klimek0dddcf72018-04-23 09:34:26 +00001049 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1050 !TheLine.startsWith(tok::r_brace));
Daniel Jasperf67c3242015-11-01 00:27:35 +00001051
1052 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Daniel Jaspera1036e52015-10-28 01:08:22 +00001053 Indent != TheLine.First->OriginalColumn;
Manuel Klimekec5c3db2015-05-07 12:26:30 +00001054 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001055 // We cannot format this line; if the reason is that the line had a
1056 // parsing error, remember that.
Krasimir Georgievbcda54b2017-04-21 14:35:20 +00001057 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1058 Status->FormatComplete = false;
1059 Status->Line =
1060 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1061 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001062
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001063 if (ShouldFormat && TheLine.Type != LT_Invalid) {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001064 if (!DryRun) {
1065 bool LastLine = Line->First->is(tok::eof);
Krasimir Georgiev62103052018-04-19 13:02:15 +00001066 formatFirstToken(TheLine, PreviousLine, Lines, Indent,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001067 LastLine ? LastStartColumn : NextStartColumn + Indent);
1068 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001069
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001070 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1071 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1072 bool FitsIntoOneLine =
1073 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
Martin Probst0cd74ee2016-06-13 16:39:50 +00001074 (TheLine.Type == LT_ImportStatement &&
1075 (Style.Language != FormatStyle::LK_JavaScript ||
1076 !Style.JavaScriptWrapImports));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001077 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +00001078 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001079 .formatLine(TheLine, NextStartColumn + Indent,
1080 FirstLine ? FirstStartColumn : 0, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001081 else if (FitsIntoOneLine)
1082 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001083 .formatLine(TheLine, NextStartColumn + Indent,
1084 FirstLine ? FirstStartColumn : 0, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001085 else
Manuel Klimekd3585db2015-05-11 08:21:35 +00001086 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001087 .formatLine(TheLine, NextStartColumn + Indent,
1088 FirstLine ? FirstStartColumn : 0, DryRun);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001089 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
Daniel Jasper0df50932014-12-10 19:00:42 +00001090 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001091 // If no token in the current line is affected, we still need to format
1092 // affected children.
1093 if (TheLine.ChildrenAffected)
Daniel Jasper35ca66d2016-02-29 12:26:20 +00001094 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1095 if (!Tok->Children.empty())
1096 format(Tok->Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +00001097
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001098 // Adapt following lines on the current indent level to the same level
1099 // unless the current \c AnnotatedLine is not at the beginning of a line.
1100 bool StartsNewLine =
1101 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1102 if (StartsNewLine)
1103 IndentTracker.adjustToUnmodifiedLine(TheLine);
1104 if (!DryRun) {
1105 bool ReformatLeadingWhitespace =
1106 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1107 TheLine.LeadingEmptyLinesAffected);
1108 // Format the first token.
1109 if (ReformatLeadingWhitespace)
Krasimir Georgiev62103052018-04-19 13:02:15 +00001110 formatFirstToken(TheLine, PreviousLine, Lines,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001111 TheLine.First->OriginalColumn,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001112 TheLine.First->OriginalColumn);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001113 else
1114 Whitespaces->addUntouchableToken(*TheLine.First,
1115 TheLine.InPPDirective);
1116
1117 // Notify the WhitespaceManager about the unchanged whitespace.
1118 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +00001119 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +00001120 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001121 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001122 RangeMinLevel = UINT_MAX;
Daniel Jasper0df50932014-12-10 19:00:42 +00001123 }
Daniel Jasperd1c13732015-01-23 19:37:25 +00001124 if (!DryRun)
1125 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001126 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +00001127 }
1128 PenaltyCache[CacheKey] = Penalty;
1129 return Penalty;
1130}
1131
Krasimir Georgiev62103052018-04-19 13:02:15 +00001132void UnwrappedLineFormatter::formatFirstToken(
1133 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1134 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1135 unsigned NewlineIndent) {
Manuel Klimek89628f62017-09-20 09:51:03 +00001136 FormatToken &RootToken = *Line.First;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001137 if (RootToken.is(tok::eof)) {
1138 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001139 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1140 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1141 TokenIndent);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001142 return;
1143 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001144 unsigned Newlines =
1145 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1146 // Remove empty lines before "}" where applicable.
1147 if (RootToken.is(tok::r_brace) &&
1148 (!RootToken.Next ||
Krasimir Georgiev62103052018-04-19 13:02:15 +00001149 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1150 // Do not remove empty lines before namespace closing "}".
1151 !getNamespaceToken(&Line, Lines))
Daniel Jasper0df50932014-12-10 19:00:42 +00001152 Newlines = std::min(Newlines, 1u);
Martin Probsta004b3f2017-11-17 18:06:33 +00001153 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1154 if (PreviousLine == nullptr && Line.Level > 0)
1155 Newlines = std::min(Newlines, 1u);
Daniel Jasper0df50932014-12-10 19:00:42 +00001156 if (Newlines == 0 && !RootToken.IsFirst)
1157 Newlines = 1;
1158 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1159 Newlines = 0;
1160
1161 // Remove empty lines after "{".
1162 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1163 PreviousLine->Last->is(tok::l_brace) &&
Sam McCall6f3778c2018-09-05 07:44:02 +00001164 !PreviousLine->startsWithNamespace() &&
Daniel Jasper0df50932014-12-10 19:00:42 +00001165 !startsExternCBlock(*PreviousLine))
1166 Newlines = 1;
1167
1168 // Insert extra new line before access specifiers.
1169 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1170 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1171 ++Newlines;
1172
1173 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +00001174 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1175 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +00001176 Newlines = std::min(1u, Newlines);
1177
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00001178 if (Newlines)
1179 Indent = NewlineIndent;
1180
1181 // Preprocessor directives get indented after the hash, if indented.
1182 if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement)
1183 Indent = 0;
1184
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001185 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1186 Line.InPPDirective &&
1187 !RootToken.HasUnescapedNewline);
Daniel Jasper0df50932014-12-10 19:00:42 +00001188}
1189
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001190unsigned
1191UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1192 const AnnotatedLine *NextLine) const {
1193 // In preprocessor directives reserve two chars for trailing " \" if the
1194 // next line continues the preprocessor directive.
1195 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +00001196 InPPDirective &&
1197 // If there is no next line, this is likely a child line and the parent
1198 // continues the preprocessor directive.
1199 (!NextLine ||
1200 (NextLine->InPPDirective &&
1201 // If there is an unescaped newline between this line and the next, the
1202 // next line starts a new preprocessor directive.
1203 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001204 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +00001205}
1206
Daniel Jasper0df50932014-12-10 19:00:42 +00001207} // namespace format
1208} // namespace clang