blob: 1f5523e130c0a493ae289249da325884c5e565f3 [file] [log] [blame]
Daniel Jasper0df50932014-12-10 19:00:42 +00001//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "UnwrappedLineFormatter.h"
11#include "WhitespaceManager.h"
12#include "llvm/Support/Debug.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000013#include <queue>
Daniel Jasper0df50932014-12-10 19:00:42 +000014
15#define DEBUG_TYPE "format-formatter"
16
17namespace clang {
18namespace format {
19
20namespace {
21
22bool startsExternCBlock(const AnnotatedLine &Line) {
23 const FormatToken *Next = Line.First->getNextNonComment();
24 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000025 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
Daniel Jasper0df50932014-12-10 19:00:42 +000026 NextNext && NextNext->is(tok::l_brace);
27}
28
Manuel Klimek3d3ea842015-05-12 09:23:57 +000029/// \brief Tracks the indent level of \c AnnotatedLines across levels.
30///
31/// \c nextLine must be called for each \c AnnotatedLine, after which \c
32/// getIndent() will return the indent for the last line \c nextLine was called
33/// with.
34/// If the line is not formatted (and thus the indent does not change), calling
35/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
36/// subsequent lines on the same level to be indented at the same level as the
37/// given line.
38class LevelIndentTracker {
39public:
40 LevelIndentTracker(const FormatStyle &Style,
41 const AdditionalKeywords &Keywords, unsigned StartLevel,
42 int AdditionalIndent)
Daniel Jasper5fc133e2015-05-12 10:16:02 +000043 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000044 for (unsigned i = 0; i != StartLevel; ++i)
45 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
46 }
47
48 /// \brief Returns the indent for the current line.
49 unsigned getIndent() const { return Indent; }
50
51 /// \brief Update the indent state given that \p Line is going to be formatted
52 /// next.
53 void nextLine(const AnnotatedLine &Line) {
54 Offset = getIndentOffset(*Line.First);
Manuel Klimekf0c95b32015-06-11 10:14:13 +000055 // Update the indent level cache size so that we can rely on it
56 // having the right size in adjustToUnmodifiedline.
57 while (IndentForLevel.size() <= Line.Level)
58 IndentForLevel.push_back(-1);
Manuel Klimek3d3ea842015-05-12 09:23:57 +000059 if (Line.InPPDirective) {
Daniel Jasper5fc133e2015-05-12 10:16:02 +000060 Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
Manuel Klimek3d3ea842015-05-12 09:23:57 +000061 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +000062 IndentForLevel.resize(Line.Level + 1);
63 Indent = getIndent(IndentForLevel, Line.Level);
64 }
65 if (static_cast<int>(Indent) + Offset >= 0)
66 Indent += Offset;
67 }
68
Francois Ferrande56a8292017-06-14 12:29:47 +000069 /// \brief Update the indent state given that \p Line indent should be
70 /// skipped.
71 void skipLine(const AnnotatedLine &Line) {
72 while (IndentForLevel.size() <= Line.Level)
73 IndentForLevel.push_back(Indent);
74 }
75
Manuel Klimek3d3ea842015-05-12 09:23:57 +000076 /// \brief Update the level indent to adapt to the given \p Line.
77 ///
78 /// When a line is not formatted, we move the subsequent lines on the same
79 /// level to the same indent.
80 /// Note that \c nextLine must have been called before this method.
81 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
82 unsigned LevelIndent = Line.First->OriginalColumn;
83 if (static_cast<int>(LevelIndent) - Offset >= 0)
84 LevelIndent -= Offset;
Daniel Jaspere285b8d2015-06-17 09:43:56 +000085 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
Manuel Klimek3d3ea842015-05-12 09:23:57 +000086 !Line.InPPDirective)
87 IndentForLevel[Line.Level] = LevelIndent;
88 }
89
90private:
91 /// \brief Get the offset of the line relatively to the level.
92 ///
93 /// For example, 'public:' labels in classes are offset by 1 or 2
94 /// characters to the left from their level.
95 int getIndentOffset(const FormatToken &RootToken) {
96 if (Style.Language == FormatStyle::LK_Java ||
97 Style.Language == FormatStyle::LK_JavaScript)
98 return 0;
99 if (RootToken.isAccessSpecifier(false) ||
100 RootToken.isObjCAccessSpecifier() ||
Daniel Jaspera00de632015-12-01 12:05:04 +0000101 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
102 RootToken.Next && RootToken.Next->is(tok::colon)))
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000103 return Style.AccessModifierOffset;
104 return 0;
105 }
106
107 /// \brief Get the indent of \p Level from \p IndentForLevel.
108 ///
109 /// \p IndentForLevel must contain the indent for the level \c l
110 /// at \p IndentForLevel[l], or a value < 0 if the indent for
111 /// that level is unknown.
112 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
113 if (IndentForLevel[Level] != -1)
114 return IndentForLevel[Level];
115 if (Level == 0)
116 return 0;
117 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
118 }
119
120 const FormatStyle &Style;
121 const AdditionalKeywords &Keywords;
Daniel Jasper56807c12015-05-12 11:14:06 +0000122 const unsigned AdditionalIndent;
Daniel Jasper5fc133e2015-05-12 10:16:02 +0000123
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000124 /// \brief The indent in characters for each level.
125 std::vector<int> IndentForLevel;
126
127 /// \brief Offset of the current line relative to the indent level.
128 ///
129 /// For example, the 'public' keywords is often indented with a negative
130 /// offset.
131 int Offset = 0;
132
133 /// \brief The current line's indent.
134 unsigned Indent = 0;
135};
136
Francois Ferrande56a8292017-06-14 12:29:47 +0000137bool isNamespaceDeclaration(const AnnotatedLine *Line) {
138 const FormatToken *NamespaceTok = Line->First;
Francois Ferrandad722562017-06-30 20:25:55 +0000139 return NamespaceTok && NamespaceTok->getNamespaceToken();
Francois Ferrande56a8292017-06-14 12:29:47 +0000140}
141
142bool isEndOfNamespace(const AnnotatedLine *Line,
143 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
144 if (!Line->startsWith(tok::r_brace))
145 return false;
146 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
147 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
148 return false;
149 assert(StartLineIndex < AnnotatedLines.size());
150 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]);
151}
152
Daniel Jasper0df50932014-12-10 19:00:42 +0000153class LineJoiner {
154public:
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000155 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
156 const SmallVectorImpl<AnnotatedLine *> &Lines)
Francois Ferrande56a8292017-06-14 12:29:47 +0000157 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
158 AnnotatedLines(Lines) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000159
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000160 /// \brief Returns the next line, merging multiple lines into one if possible.
161 const AnnotatedLine *getNextMergedLine(bool DryRun,
162 LevelIndentTracker &IndentTracker) {
163 if (Next == End)
164 return nullptr;
165 const AnnotatedLine *Current = *Next;
166 IndentTracker.nextLine(*Current);
167 unsigned MergedLines =
Francois Ferrande56a8292017-06-14 12:29:47 +0000168 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:
Daniel Jasper0df50932014-12-10 19:00:42 +0000183 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
184 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
231 ? tryMergeSimpleBlock(I, E, Limit) : 0;
232
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,
236 Keywords.kw_interface))
237 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
238 ? tryMergeSimpleBlock(I, E, Limit) : 0;
239 }
240
Daniel Jasper0df50932014-12-10 19:00:42 +0000241 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
242 // If necessary, change to something smarter.
243 bool MergeShortFunctions =
244 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
Daniel Jasper20580fd2015-06-11 13:31:45 +0000245 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000246 I[1]->First->is(tok::r_brace)) ||
Francois Ferrandd3f0e3d2017-06-21 13:56:02 +0000247 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000248 TheLine->Level != 0);
249
Francois Ferrande56a8292017-06-14 12:29:47 +0000250 if (Style.CompactNamespaces) {
251 if (isNamespaceDeclaration(TheLine)) {
252 int i = 0;
253 unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
254 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) &&
255 closingLine == I[i + 1]->MatchingOpeningBlockLineIndex &&
256 I[i + 1]->Last->TotalLength < Limit;
257 i++, closingLine--) {
258 // No extra indent for compacted namespaces
259 IndentTracker.skipLine(*I[i + 1]);
260
261 Limit -= I[i + 1]->Last->TotalLength;
262 }
263 return i;
264 }
265
266 if (isEndOfNamespace(TheLine, AnnotatedLines)) {
267 int i = 0;
268 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
269 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) &&
270 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
271 i++, openingLine--) {
272 // No space between consecutive braces
273 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
274
275 // Indent like the outer-most namespace
276 IndentTracker.nextLine(*I[i + 1]);
277 }
278 return i;
279 }
280 }
281
Daniel Jasper0df50932014-12-10 19:00:42 +0000282 if (TheLine->Last->is(TT_FunctionLBrace) &&
283 TheLine->First != TheLine->Last) {
284 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
285 }
286 if (TheLine->Last->is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000287 return !Style.BraceWrapping.AfterFunction
Daniel Jasper0df50932014-12-10 19:00:42 +0000288 ? tryMergeSimpleBlock(I, E, Limit)
289 : 0;
290 }
291 if (I[1]->First->is(TT_FunctionLBrace) &&
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000292 Style.BraceWrapping.AfterFunction) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000293 if (I[1]->Last->is(TT_LineComment))
294 return 0;
295
296 // Check for Limit <= 2 to account for the " {".
297 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
298 return 0;
299 Limit -= 2;
300
301 unsigned MergedLines = 0;
Francois Ferrand2a81ca82017-06-13 07:02:43 +0000302 if (MergeShortFunctions ||
303 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
304 I[1]->First == I[1]->Last && I + 2 != E &&
305 I[2]->First->is(tok::r_brace))) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000306 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
307 // If we managed to merge the block, count the function header, which is
308 // on a separate line.
309 if (MergedLines > 0)
310 ++MergedLines;
311 }
312 return MergedLines;
313 }
314 if (TheLine->First->is(tok::kw_if)) {
315 return Style.AllowShortIfStatementsOnASingleLine
316 ? tryMergeSimpleControlStatement(I, E, Limit)
317 : 0;
318 }
319 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
320 return Style.AllowShortLoopsOnASingleLine
321 ? tryMergeSimpleControlStatement(I, E, Limit)
322 : 0;
323 }
324 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
325 return Style.AllowShortCaseLabelsOnASingleLine
326 ? tryMergeShortCaseLabels(I, E, Limit)
327 : 0;
328 }
329 if (TheLine->InPPDirective &&
330 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
331 return tryMergeSimplePPDirective(I, E, Limit);
332 }
333 return 0;
334 }
335
Daniel Jasper0df50932014-12-10 19:00:42 +0000336 unsigned
337 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
338 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
339 unsigned Limit) {
340 if (Limit == 0)
341 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000342 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
343 return 0;
344 if (1 + I[1]->Last->TotalLength > Limit)
345 return 0;
346 return 1;
347 }
348
349 unsigned tryMergeSimpleControlStatement(
350 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
351 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
352 if (Limit == 0)
353 return 0;
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000354 if (Style.BraceWrapping.AfterControlStatement &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000355 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
356 return 0;
357 if (I[1]->InPPDirective != (*I)->InPPDirective ||
358 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
359 return 0;
360 Limit = limitConsideringMacros(I + 1, E, Limit);
361 AnnotatedLine &Line = **I;
362 if (Line.Last->isNot(tok::r_paren))
363 return 0;
364 if (1 + I[1]->Last->TotalLength > Limit)
365 return 0;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000366 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
367 TT_LineComment))
Daniel Jasper0df50932014-12-10 19:00:42 +0000368 return 0;
369 // Only inline simple if's (no nested if or else).
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000370 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000371 I[2]->First->is(tok::kw_else))
372 return 0;
373 return 1;
374 }
375
Manuel Klimekd3585db2015-05-11 08:21:35 +0000376 unsigned
377 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
378 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
379 unsigned Limit) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000380 if (Limit == 0 || I + 1 == E ||
381 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
382 return 0;
383 unsigned NumStmts = 0;
384 unsigned Length = 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000385 bool EndsWithComment = false;
Daniel Jasper0df50932014-12-10 19:00:42 +0000386 bool InPPDirective = I[0]->InPPDirective;
Francois Ferranda64ba702017-07-28 07:56:18 +0000387 const unsigned Level = I[0]->Level;
Daniel Jasper0df50932014-12-10 19:00:42 +0000388 for (; NumStmts < 3; ++NumStmts) {
389 if (I + 1 + NumStmts == E)
390 break;
391 const AnnotatedLine *Line = I[1 + NumStmts];
392 if (Line->InPPDirective != InPPDirective)
393 break;
394 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
395 break;
396 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
Francois Ferranda64ba702017-07-28 07:56:18 +0000397 tok::kw_while) ||
398 EndsWithComment)
Daniel Jasper0df50932014-12-10 19:00:42 +0000399 return 0;
Francois Ferranda64ba702017-07-28 07:56:18 +0000400 if (Line->First->is(tok::comment)) {
401 if (Level != Line->Level)
402 return 0;
403 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
404 for (; J != E; ++J) {
405 Line = *J;
406 if (Line->InPPDirective != InPPDirective)
407 break;
408 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
409 break;
410 if (Line->First->isNot(tok::comment) || Level != Line->Level)
411 return 0;
412 }
413 break;
414 }
415 if (Line->Last->is(tok::comment))
416 EndsWithComment = true;
Daniel Jasper0df50932014-12-10 19:00:42 +0000417 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
418 }
419 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
420 return 0;
421 return NumStmts;
422 }
423
424 unsigned
425 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
426 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
427 unsigned Limit) {
428 AnnotatedLine &Line = **I;
429
430 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000431 // FIXME: If an option to allow short exception handling clauses on a single
432 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000433 if (Style.Language != FormatStyle::LK_Java &&
434 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
435 return 0;
436
437 // Check that the current line allows merging. This depends on whether we
438 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000439 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
440 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000441 return 0;
442 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000443 tok::kw___try, tok::kw_catch, tok::kw___finally,
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000444 tok::kw_for, tok::r_brace, Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000445 if (!Style.AllowShortBlocksOnASingleLine)
446 return 0;
447 if (!Style.AllowShortIfStatementsOnASingleLine &&
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000448 Line.startsWith(tok::kw_if))
Daniel Jasper0df50932014-12-10 19:00:42 +0000449 return 0;
450 if (!Style.AllowShortLoopsOnASingleLine &&
451 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
452 return 0;
453 // FIXME: Consider an option to allow short exception handling clauses on
454 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000455 // FIXME: This isn't covered by tests.
456 // FIXME: For catch, __except, __finally the first token on the line
457 // is '}', so this isn't correct here.
458 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
459 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000460 return 0;
461 }
462
463 FormatToken *Tok = I[1]->First;
464 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
465 (Tok->getNextNonComment() == nullptr ||
466 Tok->getNextNonComment()->is(tok::semi))) {
467 // We merge empty blocks even if the line exceeds the column limit.
468 Tok->SpacesRequiredBefore = 0;
469 Tok->CanBreakBefore = true;
470 return 1;
Daniel Jaspere285b8d2015-06-17 09:43:56 +0000471 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
Daniel Jasper0df50932014-12-10 19:00:42 +0000472 !startsExternCBlock(Line)) {
473 // We don't merge short records.
Daniel Jasperf92659e2017-06-19 07:45:41 +0000474 FormatToken *RecordTok =
475 Line.First->is(tok::kw_typedef) ? Line.First->Next : Line.First;
476 if (RecordTok &&
477 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
478 Keywords.kw_interface))
Daniel Jasper0df50932014-12-10 19:00:42 +0000479 return 0;
480
481 // Check that we still have three lines and they fit into the limit.
482 if (I + 2 == E || I[2]->Type == LT_Invalid)
483 return 0;
484 Limit = limitConsideringMacros(I + 2, E, Limit);
485
486 if (!nextTwoLinesFitInto(I, Limit))
487 return 0;
488
489 // Second, check that the next line does not contain any braces - if it
490 // does, readability declines when putting it into a single line.
491 if (I[1]->Last->is(TT_LineComment))
492 return 0;
493 do {
494 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
495 return 0;
496 Tok = Tok->Next;
497 } while (Tok);
498
499 // Last, check that the third line starts with a closing brace.
500 Tok = I[2]->First;
501 if (Tok->isNot(tok::r_brace))
502 return 0;
503
Daniel Jaspere9f53572015-04-30 09:24:17 +0000504 // Don't merge "if (a) { .. } else {".
505 if (Tok->Next && Tok->Next->is(tok::kw_else))
506 return 0;
507
Daniel Jasper0df50932014-12-10 19:00:42 +0000508 return 2;
509 }
510 return 0;
511 }
512
513 /// Returns the modified column limit for \p I if it is inside a macro and
514 /// needs a trailing '\'.
515 unsigned
516 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
517 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
518 unsigned Limit) {
519 if (I[0]->InPPDirective && I + 1 != E &&
520 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
521 return Limit < 2 ? 0 : Limit - 2;
522 }
523 return Limit;
524 }
525
526 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
527 unsigned Limit) {
528 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
529 return false;
530 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
531 }
532
533 bool containsMustBreak(const AnnotatedLine *Line) {
534 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
535 if (Tok->MustBreakBefore)
536 return true;
537 }
538 return false;
539 }
540
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000541 void join(AnnotatedLine &A, const AnnotatedLine &B) {
542 assert(!A.Last->Next);
543 assert(!B.First->Previous);
544 if (B.Affected)
545 A.Affected = true;
546 A.Last->Next = B.First;
547 B.First->Previous = A.Last;
548 B.First->CanBreakBefore = true;
549 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
550 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
551 Tok->TotalLength += LengthA;
552 A.Last = Tok;
553 }
554 }
555
Daniel Jasper0df50932014-12-10 19:00:42 +0000556 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000557 const AdditionalKeywords &Keywords;
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000558 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000559
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +0000560 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
Francois Ferrande56a8292017-06-14 12:29:47 +0000561 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
Daniel Jasper0df50932014-12-10 19:00:42 +0000562};
563
Daniel Jasperd1c13732015-01-23 19:37:25 +0000564static void markFinalized(FormatToken *Tok) {
565 for (; Tok; Tok = Tok->Next) {
566 Tok->Finalized = true;
567 for (AnnotatedLine *Child : Tok->Children)
568 markFinalized(Child->First);
569 }
570}
571
Manuel Klimekd3585db2015-05-11 08:21:35 +0000572#ifndef NDEBUG
573static void printLineState(const LineState &State) {
574 llvm::dbgs() << "State: ";
575 for (const ParenState &P : State.Stack) {
576 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
577 << " ";
578 }
579 llvm::dbgs() << State.NextToken->TokenText << "\n";
580}
581#endif
582
583/// \brief Base class for classes that format one \c AnnotatedLine.
584class LineFormatter {
585public:
586 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
587 const FormatStyle &Style,
588 UnwrappedLineFormatter *BlockFormatter)
589 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
590 BlockFormatter(BlockFormatter) {}
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000591 virtual ~LineFormatter() {}
Manuel Klimekd3585db2015-05-11 08:21:35 +0000592
593 /// \brief Formats an \c AnnotatedLine and returns the penalty.
594 ///
595 /// If \p DryRun is \c false, directly applies the changes.
596 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
597 bool DryRun) = 0;
598
599protected:
600 /// \brief If the \p State's next token is an r_brace closing a nested block,
601 /// format the nested block before it.
602 ///
603 /// Returns \c true if all children could be placed successfully and adapts
604 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
605 /// creates changes using \c Whitespaces.
606 ///
607 /// The crucial idea here is that children always get formatted upon
608 /// encountering the closing brace right after the nested block. Now, if we
609 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
610 /// \c false), the entire block has to be kept on the same line (which is only
611 /// possible if it fits on the line, only contains a single statement, etc.
612 ///
613 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
614 /// break after the "{", format all lines with correct indentation and the put
615 /// the closing "}" on yet another new line.
616 ///
617 /// This enables us to keep the simple structure of the
618 /// \c UnwrappedLineFormatter, where we only have two options for each token:
619 /// break or don't break.
620 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
621 unsigned &Penalty) {
622 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
623 FormatToken &Previous = *State.NextToken->Previous;
624 if (!LBrace || LBrace->isNot(tok::l_brace) ||
625 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
626 // The previous token does not open a block. Nothing to do. We don't
627 // assert so that we can simply call this function for all tokens.
628 return true;
629
630 if (NewLine) {
631 int AdditionalIndent = State.Stack.back().Indent -
632 Previous.Children[0]->Level * Style.IndentWidth;
633
634 Penalty +=
635 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
636 /*FixBadIndentation=*/true);
637 return true;
638 }
639
640 if (Previous.Children[0]->First->MustBreakBefore)
641 return false;
642
Manuel Klimekd3585db2015-05-11 08:21:35 +0000643 // Cannot merge into one line if this line ends on a comment.
644 if (Previous.is(tok::comment))
645 return false;
646
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000647 // Cannot merge multiple statements into a single line.
648 if (Previous.Children.size() > 1)
649 return false;
650
651 const AnnotatedLine *Child = Previous.Children[0];
Manuel Klimekd3585db2015-05-11 08:21:35 +0000652 // We can't put the closing "}" on a line with a trailing comment.
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000653 if (Child->Last->isTrailingComment())
Manuel Klimekd3585db2015-05-11 08:21:35 +0000654 return false;
655
656 // If the child line exceeds the column limit, we wouldn't want to merge it.
657 // We add +2 for the trailing " }".
658 if (Style.ColumnLimit > 0 &&
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000659 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000660 return false;
661
662 if (!DryRun) {
663 Whitespaces->replaceWhitespace(
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000664 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
Manuel Klimekd3585db2015-05-11 08:21:35 +0000665 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
666 }
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000667 Penalty += formatLine(*Child, State.Column + 1, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000668
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000669 State.Column += 1 + Child->Last->TotalLength;
Manuel Klimekd3585db2015-05-11 08:21:35 +0000670 return true;
671 }
672
673 ContinuationIndenter *Indenter;
674
675private:
676 WhitespaceManager *Whitespaces;
677 const FormatStyle &Style;
678 UnwrappedLineFormatter *BlockFormatter;
679};
680
681/// \brief Formatter that keeps the existing line breaks.
682class NoColumnLimitLineFormatter : public LineFormatter {
683public:
684 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
685 WhitespaceManager *Whitespaces,
686 const FormatStyle &Style,
687 UnwrappedLineFormatter *BlockFormatter)
688 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
689
690 /// \brief Formats the line, simply keeping all of the input's line breaking
691 /// decisions.
692 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
693 bool DryRun) override {
694 assert(!DryRun);
695 LineState State =
696 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false);
697 while (State.NextToken) {
698 bool Newline =
699 Indenter->mustBreak(State) ||
700 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
701 unsigned Penalty = 0;
702 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
703 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
704 }
705 return 0;
706 }
707};
708
709/// \brief Formatter that puts all tokens into a single line without breaks.
710class NoLineBreakFormatter : public LineFormatter {
711public:
712 NoLineBreakFormatter(ContinuationIndenter *Indenter,
713 WhitespaceManager *Whitespaces, const FormatStyle &Style,
714 UnwrappedLineFormatter *BlockFormatter)
715 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
716
717 /// \brief Puts all tokens into a single line.
718 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Hans Wennborg7eb54642015-09-10 17:07:54 +0000719 bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000720 unsigned Penalty = 0;
721 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
722 while (State.NextToken) {
723 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
Krasimir Georgiev994b6c92017-05-18 08:07:52 +0000724 Indenter->addTokenToState(
725 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
Manuel Klimekd3585db2015-05-11 08:21:35 +0000726 }
727 return Penalty;
728 }
729};
730
731/// \brief Finds the best way to break lines.
732class OptimizingLineFormatter : public LineFormatter {
733public:
734 OptimizingLineFormatter(ContinuationIndenter *Indenter,
735 WhitespaceManager *Whitespaces,
736 const FormatStyle &Style,
737 UnwrappedLineFormatter *BlockFormatter)
738 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
739
740 /// \brief Formats the line by finding the best line breaks with line lengths
741 /// below the column limit.
742 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
Hans Wennborg7eb54642015-09-10 17:07:54 +0000743 bool DryRun) override {
Manuel Klimekd3585db2015-05-11 08:21:35 +0000744 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
745
746 // If the ObjC method declaration does not fit on a line, we should format
747 // it with one arg per line.
748 if (State.Line->Type == LT_ObjCMethodDecl)
749 State.Stack.back().BreakBeforeParameter = true;
750
751 // Find best solution in solution space.
752 return analyzeSolutionSpace(State, DryRun);
753 }
754
755private:
756 struct CompareLineStatePointers {
757 bool operator()(LineState *obj1, LineState *obj2) const {
758 return *obj1 < *obj2;
759 }
760 };
761
762 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
763 ///
764 /// In case of equal penalties, we want to prefer states that were inserted
765 /// first. During state generation we make sure that we insert states first
766 /// that break the line as late as possible.
767 typedef std::pair<unsigned, unsigned> OrderedPenalty;
768
769 /// \brief An edge in the solution space from \c Previous->State to \c State,
770 /// inserting a newline dependent on the \c NewLine.
771 struct StateNode {
772 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
773 : State(State), NewLine(NewLine), Previous(Previous) {}
774 LineState State;
775 bool NewLine;
776 StateNode *Previous;
777 };
778
779 /// \brief An item in the prioritized BFS search queue. The \c StateNode's
780 /// \c State has the given \c OrderedPenalty.
781 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
782
783 /// \brief The BFS queue type.
784 typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
785 std::greater<QueueItem>> QueueType;
786
787 /// \brief Analyze the entire solution space starting from \p InitialState.
788 ///
789 /// This implements a variant of Dijkstra's algorithm on the graph that spans
790 /// the solution space (\c LineStates are the nodes). The algorithm tries to
791 /// find the shortest path (the one with lowest penalty) from \p InitialState
792 /// to a state where all tokens are placed. Returns the penalty.
793 ///
794 /// If \p DryRun is \c false, directly applies the changes.
795 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
796 std::set<LineState *, CompareLineStatePointers> Seen;
797
798 // Increasing count of \c StateNode items we have created. This is used to
799 // create a deterministic order independent of the container.
800 unsigned Count = 0;
801 QueueType Queue;
802
803 // Insert start element into queue.
804 StateNode *Node =
805 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
806 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
807 ++Count;
808
809 unsigned Penalty = 0;
810
811 // While not empty, take first element and follow edges.
812 while (!Queue.empty()) {
813 Penalty = Queue.top().first.first;
814 StateNode *Node = Queue.top().second;
815 if (!Node->State.NextToken) {
816 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
817 break;
818 }
819 Queue.pop();
820
821 // Cut off the analysis of certain solutions if the analysis gets too
822 // complex. See description of IgnoreStackForComparison.
Daniel Jasper75bf2032015-10-27 22:55:55 +0000823 if (Count > 50000)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000824 Node->State.IgnoreStackForComparison = true;
825
826 if (!Seen.insert(&Node->State).second)
827 // State already examined with lower penalty.
828 continue;
829
830 FormatDecision LastFormat = Node->State.NextToken->Decision;
831 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
832 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
833 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
834 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
835 }
836
837 if (Queue.empty()) {
838 // We were unable to find a solution, do nothing.
839 // FIXME: Add diagnostic?
840 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
841 return 0;
842 }
843
844 // Reconstruct the solution.
845 if (!DryRun)
846 reconstructPath(InitialState, Queue.top().second);
847
848 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
849 DEBUG(llvm::dbgs() << "---\n");
850
851 return Penalty;
852 }
853
854 /// \brief Add the following state to the analysis queue \c Queue.
855 ///
856 /// Assume the current state is \p PreviousNode and has been reached with a
857 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
858 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
859 bool NewLine, unsigned *Count, QueueType *Queue) {
860 if (NewLine && !Indenter->canBreak(PreviousNode->State))
861 return;
862 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
863 return;
864
865 StateNode *Node = new (Allocator.Allocate())
866 StateNode(PreviousNode->State, NewLine, PreviousNode);
867 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
868 return;
869
870 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
871
872 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
873 ++(*Count);
874 }
875
876 /// \brief Applies the best formatting by reconstructing the path in the
877 /// solution space that leads to \c Best.
878 void reconstructPath(LineState &State, StateNode *Best) {
879 std::deque<StateNode *> Path;
880 // We do not need a break before the initial token.
881 while (Best->Previous) {
882 Path.push_front(Best);
883 Best = Best->Previous;
884 }
885 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
886 I != E; ++I) {
887 unsigned Penalty = 0;
888 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
889 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
890
891 DEBUG({
892 printLineState((*I)->Previous->State);
893 if ((*I)->NewLine) {
894 llvm::dbgs() << "Penalty for placing "
895 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
896 << Penalty << "\n";
897 }
898 });
899 }
900 }
901
902 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
903};
904
Hans Wennborg7eb54642015-09-10 17:07:54 +0000905} // anonymous namespace
Daniel Jasper0df50932014-12-10 19:00:42 +0000906
907unsigned
908UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
909 bool DryRun, int AdditionalIndent,
910 bool FixBadIndentation) {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000911 LineJoiner Joiner(Style, Keywords, Lines);
Daniel Jasper0df50932014-12-10 19:00:42 +0000912
913 // Try to look up already computed penalty in DryRun-mode.
914 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
915 &Lines, AdditionalIndent);
916 auto CacheIt = PenaltyCache.find(CacheKey);
917 if (DryRun && CacheIt != PenaltyCache.end())
918 return CacheIt->second;
919
920 assert(!Lines.empty());
921 unsigned Penalty = 0;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000922 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
923 AdditionalIndent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000924 const AnnotatedLine *PreviousLine = nullptr;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000925 const AnnotatedLine *NextLine = nullptr;
Daniel Jasperf67c3242015-11-01 00:27:35 +0000926
927 // The minimum level of consecutive lines that have been formatted.
928 unsigned RangeMinLevel = UINT_MAX;
Daniel Jasperf67c3242015-11-01 00:27:35 +0000929
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000930 for (const AnnotatedLine *Line =
931 Joiner.getNextMergedLine(DryRun, IndentTracker);
932 Line; Line = NextLine) {
933 const AnnotatedLine &TheLine = *Line;
934 unsigned Indent = IndentTracker.getIndent();
Daniel Jasperf67c3242015-11-01 00:27:35 +0000935
936 // We continue formatting unchanged lines to adjust their indent, e.g. if a
937 // scope was added. However, we need to carefully stop doing this when we
938 // exit the scope of affected lines to prevent indenting a the entire
939 // remaining file if it currently missing a closing brace.
940 bool ContinueFormatting =
941 TheLine.Level > RangeMinLevel ||
Daniel Jasperf83834f2015-11-02 20:02:49 +0000942 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace));
Daniel Jasperf67c3242015-11-01 00:27:35 +0000943
944 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
Daniel Jaspera1036e52015-10-28 01:08:22 +0000945 Indent != TheLine.First->OriginalColumn;
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000946 bool ShouldFormat = TheLine.Affected || FixIndentation;
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000947 // We cannot format this line; if the reason is that the line had a
948 // parsing error, remember that.
Krasimir Georgievbcda54b2017-04-21 14:35:20 +0000949 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
950 Status->FormatComplete = false;
951 Status->Line =
952 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
953 }
Daniel Jasper0df50932014-12-10 19:00:42 +0000954
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000955 if (ShouldFormat && TheLine.Type != LT_Invalid) {
956 if (!DryRun)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000957 formatFirstToken(TheLine, PreviousLine, Indent);
Daniel Jasper0df50932014-12-10 19:00:42 +0000958
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000959 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
960 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
961 bool FitsIntoOneLine =
962 TheLine.Last->TotalLength + Indent <= ColumnLimit ||
Martin Probst0cd74ee2016-06-13 16:39:50 +0000963 (TheLine.Type == LT_ImportStatement &&
964 (Style.Language != FormatStyle::LK_JavaScript ||
965 !Style.JavaScriptWrapImports));
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000966
967 if (Style.ColumnLimit == 0)
Manuel Klimekd3585db2015-05-11 08:21:35 +0000968 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
969 .formatLine(TheLine, Indent, DryRun);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000970 else if (FitsIntoOneLine)
971 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
972 .formatLine(TheLine, Indent, DryRun);
973 else
Manuel Klimekd3585db2015-05-11 08:21:35 +0000974 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
975 .formatLine(TheLine, Indent, DryRun);
Daniel Jasperf67c3242015-11-01 00:27:35 +0000976 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
Daniel Jasper0df50932014-12-10 19:00:42 +0000977 } else {
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000978 // If no token in the current line is affected, we still need to format
979 // affected children.
980 if (TheLine.ChildrenAffected)
Daniel Jasper35ca66d2016-02-29 12:26:20 +0000981 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
982 if (!Tok->Children.empty())
983 format(Tok->Children, DryRun);
Daniel Jasper0df50932014-12-10 19:00:42 +0000984
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000985 // Adapt following lines on the current indent level to the same level
986 // unless the current \c AnnotatedLine is not at the beginning of a line.
987 bool StartsNewLine =
988 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
989 if (StartsNewLine)
990 IndentTracker.adjustToUnmodifiedLine(TheLine);
991 if (!DryRun) {
992 bool ReformatLeadingWhitespace =
993 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
994 TheLine.LeadingEmptyLinesAffected);
995 // Format the first token.
996 if (ReformatLeadingWhitespace)
Daniel Jasper7d42f3f2017-01-31 11:25:01 +0000997 formatFirstToken(TheLine, PreviousLine,
998 TheLine.First->OriginalColumn);
Manuel Klimek3d3ea842015-05-12 09:23:57 +0000999 else
1000 Whitespaces->addUntouchableToken(*TheLine.First,
1001 TheLine.InPPDirective);
1002
1003 // Notify the WhitespaceManager about the unchanged whitespace.
1004 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
Daniel Jasper0df50932014-12-10 19:00:42 +00001005 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
Daniel Jasper0df50932014-12-10 19:00:42 +00001006 }
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001007 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
Daniel Jasperf67c3242015-11-01 00:27:35 +00001008 RangeMinLevel = UINT_MAX;
Daniel Jasper0df50932014-12-10 19:00:42 +00001009 }
Daniel Jasperd1c13732015-01-23 19:37:25 +00001010 if (!DryRun)
1011 markFinalized(TheLine.First);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001012 PreviousLine = &TheLine;
Daniel Jasper0df50932014-12-10 19:00:42 +00001013 }
1014 PenaltyCache[CacheKey] = Penalty;
1015 return Penalty;
1016}
1017
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001018void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line,
Daniel Jasper0df50932014-12-10 19:00:42 +00001019 const AnnotatedLine *PreviousLine,
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001020 unsigned Indent) {
1021 FormatToken& RootToken = *Line.First;
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001022 if (RootToken.is(tok::eof)) {
1023 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001024 Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0,
Krasimir Georgiev9aceafd2017-03-08 09:02:39 +00001025 /*StartOfTokenColumn=*/0);
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001026 return;
1027 }
Daniel Jasper0df50932014-12-10 19:00:42 +00001028 unsigned Newlines =
1029 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1030 // Remove empty lines before "}" where applicable.
1031 if (RootToken.is(tok::r_brace) &&
1032 (!RootToken.Next ||
1033 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
1034 Newlines = std::min(Newlines, 1u);
1035 if (Newlines == 0 && !RootToken.IsFirst)
1036 Newlines = 1;
1037 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1038 Newlines = 0;
1039
Krasimir Georgievad47c902017-08-30 14:34:57 +00001040 // Preprocessor directives get indented after the hash, if indented.
1041 if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement)
1042 Indent = 0;
1043
Daniel Jasper0df50932014-12-10 19:00:42 +00001044 // Remove empty lines after "{".
1045 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1046 PreviousLine->Last->is(tok::l_brace) &&
1047 PreviousLine->First->isNot(tok::kw_namespace) &&
1048 !startsExternCBlock(*PreviousLine))
1049 Newlines = 1;
1050
1051 // Insert extra new line before access specifiers.
1052 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
1053 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
1054 ++Newlines;
1055
1056 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +00001057 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1058 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +00001059 Newlines = std::min(1u, Newlines);
1060
Daniel Jasper7d42f3f2017-01-31 11:25:01 +00001061 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1062 Line.InPPDirective &&
1063 !RootToken.HasUnescapedNewline);
Daniel Jasper0df50932014-12-10 19:00:42 +00001064}
1065
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001066unsigned
1067UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1068 const AnnotatedLine *NextLine) const {
1069 // In preprocessor directives reserve two chars for trailing " \" if the
1070 // next line continues the preprocessor directive.
1071 bool ContinuesPPDirective =
Daniel Jasper1a028222015-05-26 07:03:42 +00001072 InPPDirective &&
1073 // If there is no next line, this is likely a child line and the parent
1074 // continues the preprocessor directive.
1075 (!NextLine ||
1076 (NextLine->InPPDirective &&
1077 // If there is an unescaped newline between this line and the next, the
1078 // next line starts a new preprocessor directive.
1079 !NextLine->First->HasUnescapedNewline));
Manuel Klimek3d3ea842015-05-12 09:23:57 +00001080 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
Daniel Jasper0df50932014-12-10 19:00:42 +00001081}
1082
Daniel Jasper0df50932014-12-10 19:00:42 +00001083} // namespace format
1084} // namespace clang