blob: 672a911d8d6bf34d17d2e1cdfdda0be383af4684 [file] [log] [blame]
Daniel Jasper0df50932014-12-10 19:00:42 +00001//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "UnwrappedLineFormatter.h"
11#include "WhitespaceManager.h"
12#include "llvm/Support/Debug.h"
13
14#define DEBUG_TYPE "format-formatter"
15
16namespace clang {
17namespace format {
18
19namespace {
20
21bool startsExternCBlock(const AnnotatedLine &Line) {
22 const FormatToken *Next = Line.First->getNextNonComment();
23 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
24 return Line.First->is(tok::kw_extern) && Next && Next->isStringLiteral() &&
25 NextNext && NextNext->is(tok::l_brace);
26}
27
28class LineJoiner {
29public:
Nico Weberfac23712015-02-04 15:26:27 +000030 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords)
31 : Style(Style), Keywords(Keywords) {}
Daniel Jasper0df50932014-12-10 19:00:42 +000032
33 /// \brief Calculates how many lines can be merged into 1 starting at \p I.
34 unsigned
35 tryFitMultipleLinesInOne(unsigned Indent,
36 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
37 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
Daniel Jasper9ecb0e92015-03-13 13:32:11 +000038 // Can't join the last line with anything.
39 if (I + 1 == E)
40 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +000041 // We can never merge stuff if there are trailing line comments.
42 const AnnotatedLine *TheLine = *I;
43 if (TheLine->Last->is(TT_LineComment))
44 return 0;
Daniel Jasper9ecb0e92015-03-13 13:32:11 +000045 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
46 return 0;
47 if (TheLine->InPPDirective &&
48 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
49 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +000050
51 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
52 return 0;
53
54 unsigned Limit =
55 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
56 // If we already exceed the column limit, we set 'Limit' to 0. The different
57 // tryMerge..() functions can then decide whether to still do merging.
58 Limit = TheLine->Last->TotalLength > Limit
59 ? 0
60 : Limit - TheLine->Last->TotalLength;
61
Daniel Jasper0df50932014-12-10 19:00:42 +000062 // FIXME: TheLine->Level != 0 might or might not be the right check to do.
63 // If necessary, change to something smarter.
64 bool MergeShortFunctions =
65 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
66 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty &&
67 I[1]->First->is(tok::r_brace)) ||
68 (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
69 TheLine->Level != 0);
70
71 if (TheLine->Last->is(TT_FunctionLBrace) &&
72 TheLine->First != TheLine->Last) {
73 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
74 }
75 if (TheLine->Last->is(tok::l_brace)) {
76 return Style.BreakBeforeBraces == FormatStyle::BS_Attach
77 ? tryMergeSimpleBlock(I, E, Limit)
78 : 0;
79 }
80 if (I[1]->First->is(TT_FunctionLBrace) &&
81 Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
82 if (I[1]->Last->is(TT_LineComment))
83 return 0;
84
85 // Check for Limit <= 2 to account for the " {".
86 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
87 return 0;
88 Limit -= 2;
89
90 unsigned MergedLines = 0;
91 if (MergeShortFunctions) {
92 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
93 // If we managed to merge the block, count the function header, which is
94 // on a separate line.
95 if (MergedLines > 0)
96 ++MergedLines;
97 }
98 return MergedLines;
99 }
100 if (TheLine->First->is(tok::kw_if)) {
101 return Style.AllowShortIfStatementsOnASingleLine
102 ? tryMergeSimpleControlStatement(I, E, Limit)
103 : 0;
104 }
105 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
106 return Style.AllowShortLoopsOnASingleLine
107 ? tryMergeSimpleControlStatement(I, E, Limit)
108 : 0;
109 }
110 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
111 return Style.AllowShortCaseLabelsOnASingleLine
112 ? tryMergeShortCaseLabels(I, E, Limit)
113 : 0;
114 }
115 if (TheLine->InPPDirective &&
116 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
117 return tryMergeSimplePPDirective(I, E, Limit);
118 }
119 return 0;
120 }
121
122private:
123 unsigned
124 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
125 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
126 unsigned Limit) {
127 if (Limit == 0)
128 return 0;
Daniel Jasper0df50932014-12-10 19:00:42 +0000129 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
130 return 0;
131 if (1 + I[1]->Last->TotalLength > Limit)
132 return 0;
133 return 1;
134 }
135
136 unsigned tryMergeSimpleControlStatement(
137 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
138 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
139 if (Limit == 0)
140 return 0;
141 if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
142 Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
143 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
144 return 0;
145 if (I[1]->InPPDirective != (*I)->InPPDirective ||
146 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
147 return 0;
148 Limit = limitConsideringMacros(I + 1, E, Limit);
149 AnnotatedLine &Line = **I;
150 if (Line.Last->isNot(tok::r_paren))
151 return 0;
152 if (1 + I[1]->Last->TotalLength > Limit)
153 return 0;
154 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
155 tok::kw_while, TT_LineComment))
156 return 0;
157 // Only inline simple if's (no nested if or else).
158 if (I + 2 != E && Line.First->is(tok::kw_if) &&
159 I[2]->First->is(tok::kw_else))
160 return 0;
161 return 1;
162 }
163
164 unsigned tryMergeShortCaseLabels(
165 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
166 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
167 if (Limit == 0 || I + 1 == E ||
168 I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
169 return 0;
170 unsigned NumStmts = 0;
171 unsigned Length = 0;
172 bool InPPDirective = I[0]->InPPDirective;
173 for (; NumStmts < 3; ++NumStmts) {
174 if (I + 1 + NumStmts == E)
175 break;
176 const AnnotatedLine *Line = I[1 + NumStmts];
177 if (Line->InPPDirective != InPPDirective)
178 break;
179 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
180 break;
181 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
182 tok::kw_while, tok::comment))
183 return 0;
184 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
185 }
186 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
187 return 0;
188 return NumStmts;
189 }
190
191 unsigned
192 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
193 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
194 unsigned Limit) {
195 AnnotatedLine &Line = **I;
196
197 // Don't merge ObjC @ keywords and methods.
Nico Weber33381f52015-02-07 01:57:32 +0000198 // FIXME: If an option to allow short exception handling clauses on a single
199 // line is added, change this to not return for @try and friends.
Daniel Jasper0df50932014-12-10 19:00:42 +0000200 if (Style.Language != FormatStyle::LK_Java &&
201 Line.First->isOneOf(tok::at, tok::minus, tok::plus))
202 return 0;
203
204 // Check that the current line allows merging. This depends on whether we
205 // are in a control flow statements as well as several style flags.
Daniel Jaspere9f53572015-04-30 09:24:17 +0000206 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
207 (Line.First->Next && Line.First->Next->is(tok::kw_else)))
Daniel Jasper0df50932014-12-10 19:00:42 +0000208 return 0;
209 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
Nico Weberfac23712015-02-04 15:26:27 +0000210 tok::kw___try, tok::kw_catch, tok::kw___finally,
211 tok::kw_for, tok::r_brace) ||
212 Line.First->is(Keywords.kw___except)) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000213 if (!Style.AllowShortBlocksOnASingleLine)
214 return 0;
215 if (!Style.AllowShortIfStatementsOnASingleLine &&
216 Line.First->is(tok::kw_if))
217 return 0;
218 if (!Style.AllowShortLoopsOnASingleLine &&
219 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
220 return 0;
221 // FIXME: Consider an option to allow short exception handling clauses on
222 // a single line.
Nico Weberfac23712015-02-04 15:26:27 +0000223 // FIXME: This isn't covered by tests.
224 // FIXME: For catch, __except, __finally the first token on the line
225 // is '}', so this isn't correct here.
226 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
227 Keywords.kw___except, tok::kw___finally))
Daniel Jasper0df50932014-12-10 19:00:42 +0000228 return 0;
229 }
230
231 FormatToken *Tok = I[1]->First;
232 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
233 (Tok->getNextNonComment() == nullptr ||
234 Tok->getNextNonComment()->is(tok::semi))) {
235 // We merge empty blocks even if the line exceeds the column limit.
236 Tok->SpacesRequiredBefore = 0;
237 Tok->CanBreakBefore = true;
238 return 1;
239 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace) &&
240 !startsExternCBlock(Line)) {
241 // We don't merge short records.
Daniel Jasper29647492015-05-05 08:12:50 +0000242 if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
243 Keywords.kw_interface))
Daniel Jasper0df50932014-12-10 19:00:42 +0000244 return 0;
245
246 // Check that we still have three lines and they fit into the limit.
247 if (I + 2 == E || I[2]->Type == LT_Invalid)
248 return 0;
249 Limit = limitConsideringMacros(I + 2, E, Limit);
250
251 if (!nextTwoLinesFitInto(I, Limit))
252 return 0;
253
254 // Second, check that the next line does not contain any braces - if it
255 // does, readability declines when putting it into a single line.
256 if (I[1]->Last->is(TT_LineComment))
257 return 0;
258 do {
259 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
260 return 0;
261 Tok = Tok->Next;
262 } while (Tok);
263
264 // Last, check that the third line starts with a closing brace.
265 Tok = I[2]->First;
266 if (Tok->isNot(tok::r_brace))
267 return 0;
268
Daniel Jaspere9f53572015-04-30 09:24:17 +0000269 // Don't merge "if (a) { .. } else {".
270 if (Tok->Next && Tok->Next->is(tok::kw_else))
271 return 0;
272
Daniel Jasper0df50932014-12-10 19:00:42 +0000273 return 2;
274 }
275 return 0;
276 }
277
278 /// Returns the modified column limit for \p I if it is inside a macro and
279 /// needs a trailing '\'.
280 unsigned
281 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
282 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
283 unsigned Limit) {
284 if (I[0]->InPPDirective && I + 1 != E &&
285 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
286 return Limit < 2 ? 0 : Limit - 2;
287 }
288 return Limit;
289 }
290
291 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
292 unsigned Limit) {
293 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
294 return false;
295 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
296 }
297
298 bool containsMustBreak(const AnnotatedLine *Line) {
299 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
300 if (Tok->MustBreakBefore)
301 return true;
302 }
303 return false;
304 }
305
306 const FormatStyle &Style;
Nico Weberfac23712015-02-04 15:26:27 +0000307 const AdditionalKeywords &Keywords;
Daniel Jasper0df50932014-12-10 19:00:42 +0000308};
309
310class NoColumnLimitFormatter {
311public:
Daniel Jasper289afc02015-04-23 09:23:17 +0000312 NoColumnLimitFormatter(ContinuationIndenter *Indenter,
313 UnwrappedLineFormatter *Formatter)
314 : Indenter(Indenter), Formatter(Formatter) {}
Daniel Jasper0df50932014-12-10 19:00:42 +0000315
316 /// \brief Formats the line starting at \p State, simply keeping all of the
317 /// input's line breaking decisions.
318 void format(unsigned FirstIndent, const AnnotatedLine *Line) {
319 LineState State =
320 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
321 while (State.NextToken) {
322 bool Newline =
323 Indenter->mustBreak(State) ||
324 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
Daniel Jasper289afc02015-04-23 09:23:17 +0000325 unsigned Penalty = 0;
326 Formatter->formatChildren(State, Newline, /*DryRun=*/false, Penalty);
Daniel Jasper0df50932014-12-10 19:00:42 +0000327 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
328 }
329 }
330
331private:
332 ContinuationIndenter *Indenter;
Daniel Jasper289afc02015-04-23 09:23:17 +0000333 UnwrappedLineFormatter *Formatter;
Daniel Jasper0df50932014-12-10 19:00:42 +0000334};
335
Daniel Jasperd1c13732015-01-23 19:37:25 +0000336
337static void markFinalized(FormatToken *Tok) {
338 for (; Tok; Tok = Tok->Next) {
339 Tok->Finalized = true;
340 for (AnnotatedLine *Child : Tok->Children)
341 markFinalized(Child->First);
342 }
343}
344
Daniel Jasper0df50932014-12-10 19:00:42 +0000345} // namespace
346
347unsigned
348UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines,
349 bool DryRun, int AdditionalIndent,
350 bool FixBadIndentation) {
Nico Weberfac23712015-02-04 15:26:27 +0000351 LineJoiner Joiner(Style, Keywords);
Daniel Jasper0df50932014-12-10 19:00:42 +0000352
353 // Try to look up already computed penalty in DryRun-mode.
354 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
355 &Lines, AdditionalIndent);
356 auto CacheIt = PenaltyCache.find(CacheKey);
357 if (DryRun && CacheIt != PenaltyCache.end())
358 return CacheIt->second;
359
360 assert(!Lines.empty());
361 unsigned Penalty = 0;
362 std::vector<int> IndentForLevel;
363 for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
364 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
365 const AnnotatedLine *PreviousLine = nullptr;
366 for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
367 E = Lines.end();
368 I != E; ++I) {
369 const AnnotatedLine &TheLine = **I;
370 const FormatToken *FirstTok = TheLine.First;
371 int Offset = getIndentOffset(*FirstTok);
372
373 // Determine indent and try to merge multiple unwrapped lines.
374 unsigned Indent;
375 if (TheLine.InPPDirective) {
376 Indent = TheLine.Level * Style.IndentWidth;
377 } else {
378 while (IndentForLevel.size() <= TheLine.Level)
379 IndentForLevel.push_back(-1);
380 IndentForLevel.resize(TheLine.Level + 1);
381 Indent = getIndent(IndentForLevel, TheLine.Level);
382 }
383 unsigned LevelIndent = Indent;
384 if (static_cast<int>(Indent) + Offset >= 0)
385 Indent += Offset;
386
387 // Merge multiple lines if possible.
388 unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
389 if (MergedLines > 0 && Style.ColumnLimit == 0) {
390 // Disallow line merging if there is a break at the start of one of the
391 // input lines.
392 for (unsigned i = 0; i < MergedLines; ++i) {
393 if (I[i + 1]->First->NewlinesBefore > 0)
394 MergedLines = 0;
395 }
396 }
397 if (!DryRun) {
398 for (unsigned i = 0; i < MergedLines; ++i) {
399 join(*I[i], *I[i + 1]);
400 }
401 }
402 I += MergedLines;
403
404 bool FixIndentation =
405 FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000406 bool ShouldFormat = TheLine.Affected || FixIndentation;
Daniel Jasper0df50932014-12-10 19:00:42 +0000407 if (TheLine.First->is(tok::eof)) {
408 if (PreviousLine && PreviousLine->Affected && !DryRun) {
409 // Remove the file's trailing whitespace.
410 unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
411 Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
412 /*IndentLevel=*/0, /*Spaces=*/0,
413 /*TargetColumn=*/0);
414 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000415 } else if (TheLine.Type != LT_Invalid && ShouldFormat) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000416 if (FirstTok->WhitespaceRange.isValid()) {
417 if (!DryRun)
418 formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level, Indent,
419 TheLine.InPPDirective);
420 } else {
421 Indent = LevelIndent = FirstTok->OriginalColumn;
422 }
423
424 // If everything fits on a single line, just put it there.
425 unsigned ColumnLimit = Style.ColumnLimit;
426 if (I + 1 != E) {
427 AnnotatedLine *NextLine = I[1];
428 if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
429 ColumnLimit = getColumnLimit(TheLine.InPPDirective);
430 }
431
432 if (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
433 TheLine.Type == LT_ImportStatement) {
434 LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
435 while (State.NextToken) {
Daniel Jasper47b35ae2015-01-29 10:47:14 +0000436 formatChildren(State, /*Newline=*/false, DryRun, Penalty);
Daniel Jasper0df50932014-12-10 19:00:42 +0000437 Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
438 }
439 } else if (Style.ColumnLimit == 0) {
Daniel Jasper289afc02015-04-23 09:23:17 +0000440 NoColumnLimitFormatter Formatter(Indenter, this);
Daniel Jasper0df50932014-12-10 19:00:42 +0000441 if (!DryRun)
442 Formatter.format(Indent, &TheLine);
443 } else {
444 Penalty += format(TheLine, Indent, DryRun);
445 }
446
447 if (!TheLine.InPPDirective)
448 IndentForLevel[TheLine.Level] = LevelIndent;
449 } else if (TheLine.ChildrenAffected) {
450 format(TheLine.Children, DryRun);
451 } else {
452 // Format the first token if necessary, and notify the WhitespaceManager
453 // about the unchanged whitespace.
454 for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
455 if (Tok == TheLine.First && (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
456 unsigned LevelIndent = Tok->OriginalColumn;
457 if (!DryRun) {
458 // Remove trailing whitespace of the previous line.
459 if ((PreviousLine && PreviousLine->Affected) ||
460 TheLine.LeadingEmptyLinesAffected) {
461 formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
462 TheLine.InPPDirective);
463 } else {
464 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
465 }
466 }
467
468 if (static_cast<int>(LevelIndent) - Offset >= 0)
469 LevelIndent -= Offset;
Daniel Jaspereb45cb72015-04-29 08:29:26 +0000470 if ((Tok->isNot(tok::comment) ||
471 IndentForLevel[TheLine.Level] == -1) &&
472 !TheLine.InPPDirective)
Daniel Jasper0df50932014-12-10 19:00:42 +0000473 IndentForLevel[TheLine.Level] = LevelIndent;
474 } else if (!DryRun) {
475 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
476 }
477 }
478 }
Manuel Klimekec5c3db2015-05-07 12:26:30 +0000479 if (TheLine.Type == LT_Invalid && ShouldFormat && IncompleteFormat)
480 *IncompleteFormat = true;
Daniel Jasperd1c13732015-01-23 19:37:25 +0000481 if (!DryRun)
482 markFinalized(TheLine.First);
Daniel Jasper0df50932014-12-10 19:00:42 +0000483 PreviousLine = *I;
484 }
485 PenaltyCache[CacheKey] = Penalty;
486 return Penalty;
487}
488
489unsigned UnwrappedLineFormatter::format(const AnnotatedLine &Line,
490 unsigned FirstIndent, bool DryRun) {
491 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
492
493 // If the ObjC method declaration does not fit on a line, we should format
494 // it with one arg per line.
495 if (State.Line->Type == LT_ObjCMethodDecl)
496 State.Stack.back().BreakBeforeParameter = true;
497
498 // Find best solution in solution space.
499 return analyzeSolutionSpace(State, DryRun);
500}
501
502void UnwrappedLineFormatter::formatFirstToken(FormatToken &RootToken,
503 const AnnotatedLine *PreviousLine,
504 unsigned IndentLevel,
505 unsigned Indent,
506 bool InPPDirective) {
507 unsigned Newlines =
508 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
509 // Remove empty lines before "}" where applicable.
510 if (RootToken.is(tok::r_brace) &&
511 (!RootToken.Next ||
512 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
513 Newlines = std::min(Newlines, 1u);
514 if (Newlines == 0 && !RootToken.IsFirst)
515 Newlines = 1;
516 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
517 Newlines = 0;
518
519 // Remove empty lines after "{".
520 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
521 PreviousLine->Last->is(tok::l_brace) &&
522 PreviousLine->First->isNot(tok::kw_namespace) &&
523 !startsExternCBlock(*PreviousLine))
524 Newlines = 1;
525
526 // Insert extra new line before access specifiers.
527 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
528 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
529 ++Newlines;
530
531 // Remove empty lines after access specifiers.
Daniel Jasperac5c97e32015-03-09 08:13:55 +0000532 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
533 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
Daniel Jasper0df50932014-12-10 19:00:42 +0000534 Newlines = std::min(1u, Newlines);
535
536 Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
537 Indent, InPPDirective &&
538 !RootToken.HasUnescapedNewline);
539}
540
541/// \brief Get the indent of \p Level from \p IndentForLevel.
542///
543/// \p IndentForLevel must contain the indent for the level \c l
544/// at \p IndentForLevel[l], or a value < 0 if the indent for
545/// that level is unknown.
546unsigned UnwrappedLineFormatter::getIndent(ArrayRef<int> IndentForLevel,
547 unsigned Level) {
548 if (IndentForLevel[Level] != -1)
549 return IndentForLevel[Level];
550 if (Level == 0)
551 return 0;
552 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
553}
554
555void UnwrappedLineFormatter::join(AnnotatedLine &A, const AnnotatedLine &B) {
556 assert(!A.Last->Next);
557 assert(!B.First->Previous);
558 if (B.Affected)
559 A.Affected = true;
560 A.Last->Next = B.First;
561 B.First->Previous = A.Last;
562 B.First->CanBreakBefore = true;
563 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
564 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
565 Tok->TotalLength += LengthA;
566 A.Last = Tok;
567 }
568}
569
570unsigned UnwrappedLineFormatter::analyzeSolutionSpace(LineState &InitialState,
571 bool DryRun) {
572 std::set<LineState *, CompareLineStatePointers> Seen;
573
574 // Increasing count of \c StateNode items we have created. This is used to
575 // create a deterministic order independent of the container.
576 unsigned Count = 0;
577 QueueType Queue;
578
579 // Insert start element into queue.
580 StateNode *Node =
581 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
582 Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
583 ++Count;
584
585 unsigned Penalty = 0;
586
587 // While not empty, take first element and follow edges.
588 while (!Queue.empty()) {
589 Penalty = Queue.top().first.first;
590 StateNode *Node = Queue.top().second;
591 if (!Node->State.NextToken) {
592 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
593 break;
594 }
595 Queue.pop();
596
597 // Cut off the analysis of certain solutions if the analysis gets too
598 // complex. See description of IgnoreStackForComparison.
599 if (Count > 10000)
600 Node->State.IgnoreStackForComparison = true;
601
602 if (!Seen.insert(&Node->State).second)
603 // State already examined with lower penalty.
604 continue;
605
606 FormatDecision LastFormat = Node->State.NextToken->Decision;
607 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
608 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
609 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
610 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
611 }
612
613 if (Queue.empty()) {
614 // We were unable to find a solution, do nothing.
615 // FIXME: Add diagnostic?
616 DEBUG(llvm::dbgs() << "Could not find a solution.\n");
617 return 0;
618 }
619
620 // Reconstruct the solution.
621 if (!DryRun)
622 reconstructPath(InitialState, Queue.top().second);
623
624 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
625 DEBUG(llvm::dbgs() << "---\n");
626
627 return Penalty;
628}
629
NAKAMURA Takumie9ac8b42014-12-17 14:46:56 +0000630#ifndef NDEBUG
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000631static void printLineState(const LineState &State) {
632 llvm::dbgs() << "State: ";
633 for (const ParenState &P : State.Stack) {
634 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent
635 << " ";
636 }
637 llvm::dbgs() << State.NextToken->TokenText << "\n";
638}
NAKAMURA Takumie9ac8b42014-12-17 14:46:56 +0000639#endif
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000640
Daniel Jasper0df50932014-12-10 19:00:42 +0000641void UnwrappedLineFormatter::reconstructPath(LineState &State,
642 StateNode *Current) {
643 std::deque<StateNode *> Path;
644 // We do not need a break before the initial token.
645 while (Current->Previous) {
646 Path.push_front(Current);
647 Current = Current->Previous;
648 }
649 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
650 I != E; ++I) {
651 unsigned Penalty = 0;
652 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
653 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
654
655 DEBUG({
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000656 printLineState((*I)->Previous->State);
Daniel Jasper0df50932014-12-10 19:00:42 +0000657 if ((*I)->NewLine) {
658 llvm::dbgs() << "Penalty for placing "
659 << (*I)->Previous->State.NextToken->Tok.getName() << ": "
660 << Penalty << "\n";
661 }
662 });
663 }
664}
665
666void UnwrappedLineFormatter::addNextStateToQueue(unsigned Penalty,
667 StateNode *PreviousNode,
668 bool NewLine, unsigned *Count,
669 QueueType *Queue) {
670 if (NewLine && !Indenter->canBreak(PreviousNode->State))
671 return;
672 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
673 return;
674
675 StateNode *Node = new (Allocator.Allocate())
676 StateNode(PreviousNode->State, NewLine, PreviousNode);
677 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
678 return;
679
680 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
681
682 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
683 ++(*Count);
684}
685
686bool UnwrappedLineFormatter::formatChildren(LineState &State, bool NewLine,
687 bool DryRun, unsigned &Penalty) {
Daniel Jasper0df50932014-12-10 19:00:42 +0000688 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
Daniel Jasper47b35ae2015-01-29 10:47:14 +0000689 FormatToken &Previous = *State.NextToken->Previous;
Daniel Jasper0df50932014-12-10 19:00:42 +0000690 if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->BlockKind != BK_Block ||
691 Previous.Children.size() == 0)
692 // The previous token does not open a block. Nothing to do. We don't
693 // assert so that we can simply call this function for all tokens.
694 return true;
695
696 if (NewLine) {
Daniel Jasper11a0ac62014-12-12 09:40:58 +0000697 int AdditionalIndent = State.Stack.back().Indent -
698 Previous.Children[0]->Level * Style.IndentWidth;
Daniel Jasper0df50932014-12-10 19:00:42 +0000699
700 Penalty += format(Previous.Children, DryRun, AdditionalIndent,
701 /*FixBadIndentation=*/true);
702 return true;
703 }
704
705 if (Previous.Children[0]->First->MustBreakBefore)
706 return false;
707
708 // Cannot merge multiple statements into a single line.
709 if (Previous.Children.size() > 1)
710 return false;
711
712 // Cannot merge into one line if this line ends on a comment.
713 if (Previous.is(tok::comment))
714 return false;
715
716 // We can't put the closing "}" on a line with a trailing comment.
717 if (Previous.Children[0]->Last->isTrailingComment())
718 return false;
719
720 // If the child line exceeds the column limit, we wouldn't want to merge it.
721 // We add +2 for the trailing " }".
722 if (Style.ColumnLimit > 0 &&
723 Previous.Children[0]->Last->TotalLength + State.Column + 2 >
724 Style.ColumnLimit)
725 return false;
726
727 if (!DryRun) {
728 Whitespaces->replaceWhitespace(
729 *Previous.Children[0]->First,
730 /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
731 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
732 }
733 Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
734
735 State.Column += 1 + Previous.Children[0]->Last->TotalLength;
736 return true;
737}
738
739} // namespace format
740} // namespace clang