Bug Summary

File:build/source/clang/lib/Format/UnwrappedLineFormatter.cpp
Warning:line 994, column 58
Access to field 'MacroParent' results in a dereference of a null pointer (loaded from variable 'LBrace')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name UnwrappedLineFormatter.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Format -I /build/source/clang/lib/Format -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1680002200 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-03-28-162341-16322-1 -x c++ /build/source/clang/lib/Format/UnwrappedLineFormatter.cpp
1//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9#include "UnwrappedLineFormatter.h"
10#include "FormatToken.h"
11#include "NamespaceEndCommentsFixer.h"
12#include "WhitespaceManager.h"
13#include "llvm/Support/Debug.h"
14#include <queue>
15
16#define DEBUG_TYPE"format-formatter" "format-formatter"
17
18namespace clang {
19namespace format {
20
21namespace {
22
23bool startsExternCBlock(const AnnotatedLine &Line) {
24 const FormatToken *Next = Line.First->getNextNonComment();
25 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
26 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
27 NextNext && NextNext->is(tok::l_brace);
28}
29
30bool isRecordLBrace(const FormatToken &Tok) {
31 return Tok.isOneOf(TT_ClassLBrace, TT_EnumLBrace, TT_RecordLBrace,
32 TT_StructLBrace, TT_UnionLBrace);
33}
34
35/// Tracks the indent level of \c AnnotatedLines across levels.
36///
37/// \c nextLine must be called for each \c AnnotatedLine, after which \c
38/// getIndent() will return the indent for the last line \c nextLine was called
39/// with.
40/// If the line is not formatted (and thus the indent does not change), calling
41/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
42/// subsequent lines on the same level to be indented at the same level as the
43/// given line.
44class LevelIndentTracker {
45public:
46 LevelIndentTracker(const FormatStyle &Style,
47 const AdditionalKeywords &Keywords, unsigned StartLevel,
48 int AdditionalIndent)
49 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
50 for (unsigned i = 0; i != StartLevel; ++i)
51 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
52 }
53
54 /// Returns the indent for the current line.
55 unsigned getIndent() const { return Indent; }
56
57 /// Update the indent state given that \p Line is going to be formatted
58 /// next.
59 void nextLine(const AnnotatedLine &Line) {
60 Offset = getIndentOffset(*Line.First);
61 // Update the indent level cache size so that we can rely on it
62 // having the right size in adjustToUnmodifiedline.
63 if (Line.Level >= IndentForLevel.size())
64 IndentForLevel.resize(Line.Level + 1, -1);
65 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None &&
66 (Line.InPPDirective ||
67 (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
68 Line.Type == LT_CommentAbovePPDirective))) {
69 unsigned PPIndentWidth =
70 (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
71 Indent = Line.InMacroBody
72 ? Line.PPLevel * PPIndentWidth +
73 (Line.Level - Line.PPLevel) * Style.IndentWidth
74 : Line.Level * PPIndentWidth;
75 Indent += AdditionalIndent;
76 } else {
77 Indent = getIndent(Line.Level);
78 }
79 if (static_cast<int>(Indent) + Offset >= 0)
80 Indent += Offset;
81 if (Line.IsContinuation)
82 Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth;
83 }
84
85 /// Update the level indent to adapt to the given \p Line.
86 ///
87 /// When a line is not formatted, we move the subsequent lines on the same
88 /// level to the same indent.
89 /// Note that \c nextLine must have been called before this method.
90 void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
91 unsigned LevelIndent = Line.First->OriginalColumn;
92 if (static_cast<int>(LevelIndent) - Offset >= 0)
93 LevelIndent -= Offset;
94 assert(Line.Level < IndentForLevel.size())(static_cast <bool> (Line.Level < IndentForLevel.size
()) ? void (0) : __assert_fail ("Line.Level < IndentForLevel.size()"
, "clang/lib/Format/UnwrappedLineFormatter.cpp", 94, __extension__
__PRETTY_FUNCTION__))
;
95 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
96 !Line.InPPDirective) {
97 IndentForLevel[Line.Level] = LevelIndent;
98 }
99 }
100
101private:
102 /// Get the offset of the line relatively to the level.
103 ///
104 /// For example, 'public:' labels in classes are offset by 1 or 2
105 /// characters to the left from their level.
106 int getIndentOffset(const FormatToken &RootToken) {
107 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
108 Style.isCSharp()) {
109 return 0;
110 }
111
112 auto IsAccessModifier = [this, &RootToken]() {
113 if (RootToken.isAccessSpecifier(Style.isCpp())) {
114 return true;
115 } else if (RootToken.isObjCAccessSpecifier()) {
116 return true;
117 }
118 // Handle Qt signals.
119 else if ((RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
120 RootToken.Next && RootToken.Next->is(tok::colon))) {
121 return true;
122 } else if (RootToken.Next &&
123 RootToken.Next->isOneOf(Keywords.kw_slots,
124 Keywords.kw_qslots) &&
125 RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) {
126 return true;
127 }
128 // Handle malformed access specifier e.g. 'private' without trailing ':'.
129 else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
130 return true;
131 }
132 return false;
133 };
134
135 if (IsAccessModifier()) {
136 // The AccessModifierOffset may be overridden by IndentAccessModifiers,
137 // in which case we take a negative value of the IndentWidth to simulate
138 // the upper indent level.
139 return Style.IndentAccessModifiers ? -Style.IndentWidth
140 : Style.AccessModifierOffset;
141 }
142 return 0;
143 }
144
145 /// Get the indent of \p Level from \p IndentForLevel.
146 ///
147 /// \p IndentForLevel must contain the indent for the level \c l
148 /// at \p IndentForLevel[l], or a value < 0 if the indent for
149 /// that level is unknown.
150 unsigned getIndent(unsigned Level) const {
151 if (IndentForLevel[Level] != -1)
152 return IndentForLevel[Level];
153 if (Level == 0)
154 return 0;
155 return getIndent(Level - 1) + Style.IndentWidth;
156 }
157
158 const FormatStyle &Style;
159 const AdditionalKeywords &Keywords;
160 const unsigned AdditionalIndent;
161
162 /// The indent in characters for each level.
163 SmallVector<int> IndentForLevel;
164
165 /// Offset of the current line relative to the indent level.
166 ///
167 /// For example, the 'public' keywords is often indented with a negative
168 /// offset.
169 int Offset = 0;
170
171 /// The current line's indent.
172 unsigned Indent = 0;
173};
174
175const FormatToken *getMatchingNamespaceToken(
176 const AnnotatedLine *Line,
177 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
178 if (!Line->startsWith(tok::r_brace))
179 return nullptr;
180 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
181 if (StartLineIndex == UnwrappedLine::kInvalidIndex)
182 return nullptr;
183 assert(StartLineIndex < AnnotatedLines.size())(static_cast <bool> (StartLineIndex < AnnotatedLines
.size()) ? void (0) : __assert_fail ("StartLineIndex < AnnotatedLines.size()"
, "clang/lib/Format/UnwrappedLineFormatter.cpp", 183, __extension__
__PRETTY_FUNCTION__))
;
184 return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
185}
186
187StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
188 const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
189 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
190}
191
192StringRef getMatchingNamespaceTokenText(
193 const AnnotatedLine *Line,
194 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
195 const FormatToken *NamespaceToken =
196 getMatchingNamespaceToken(Line, AnnotatedLines);
197 return NamespaceToken ? NamespaceToken->TokenText : StringRef();
198}
199
200class LineJoiner {
201public:
202 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
203 const SmallVectorImpl<AnnotatedLine *> &Lines)
204 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
205 AnnotatedLines(Lines) {}
206
207 /// Returns the next line, merging multiple lines into one if possible.
208 const AnnotatedLine *getNextMergedLine(bool DryRun,
209 LevelIndentTracker &IndentTracker) {
210 if (Next == End)
211 return nullptr;
212 const AnnotatedLine *Current = *Next;
213 IndentTracker.nextLine(*Current);
214 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
215 if (MergedLines > 0 && Style.ColumnLimit == 0) {
216 // Disallow line merging if there is a break at the start of one of the
217 // input lines.
218 for (unsigned i = 0; i < MergedLines; ++i)
219 if (Next[i + 1]->First->NewlinesBefore > 0)
220 MergedLines = 0;
221 }
222 if (!DryRun)
223 for (unsigned i = 0; i < MergedLines; ++i)
224 join(*Next[0], *Next[i + 1]);
225 Next = Next + MergedLines + 1;
226 return Current;
227 }
228
229private:
230 /// Calculates how many lines can be merged into 1 starting at \p I.
231 unsigned
232 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
233 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
234 SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
235 const unsigned Indent = IndentTracker.getIndent();
236
237 // Can't join the last line with anything.
238 if (I + 1 == E)
239 return 0;
240 // We can never merge stuff if there are trailing line comments.
241 const AnnotatedLine *TheLine = *I;
242 if (TheLine->Last->is(TT_LineComment))
243 return 0;
244 const auto &NextLine = *I[1];
245 if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore)
246 return 0;
247 if (TheLine->InPPDirective &&
248 (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) {
249 return 0;
250 }
251
252 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
253 return 0;
254
255 unsigned Limit =
256 Style.ColumnLimit == 0 ? UINT_MAX(2147483647 *2U +1U) : Style.ColumnLimit - Indent;
257 // If we already exceed the column limit, we set 'Limit' to 0. The different
258 // tryMerge..() functions can then decide whether to still do merging.
259 Limit = TheLine->Last->TotalLength > Limit
260 ? 0
261 : Limit - TheLine->Last->TotalLength;
262
263 if (TheLine->Last->is(TT_FunctionLBrace) &&
264 TheLine->First == TheLine->Last &&
265 !Style.BraceWrapping.SplitEmptyFunction &&
266 NextLine.First->is(tok::r_brace)) {
267 return tryMergeSimpleBlock(I, E, Limit);
268 }
269
270 const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr;
271 // Handle empty record blocks where the brace has already been wrapped.
272 if (PreviousLine && TheLine->Last->is(tok::l_brace) &&
273 TheLine->First == TheLine->Last) {
274 bool EmptyBlock = NextLine.First->is(tok::r_brace);
275
276 const FormatToken *Tok = PreviousLine->First;
277 if (Tok && Tok->is(tok::comment))
278 Tok = Tok->getNextNonComment();
279
280 if (Tok && Tok->getNamespaceToken()) {
281 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
282 ? tryMergeSimpleBlock(I, E, Limit)
283 : 0;
284 }
285
286 if (Tok && Tok->is(tok::kw_typedef))
287 Tok = Tok->getNextNonComment();
288 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
289 tok::kw_extern, Keywords.kw_interface)) {
290 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
291 ? tryMergeSimpleBlock(I, E, Limit)
292 : 0;
293 }
294
295 if (Tok && Tok->is(tok::kw_template) &&
296 Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
297 return 0;
298 }
299 }
300
301 auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine,
302 TheLine]() {
303 if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All)
304 return true;
305 if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
306 NextLine.First->is(tok::r_brace)) {
307 return true;
308 }
309
310 if (Style.AllowShortFunctionsOnASingleLine &
311 FormatStyle::SFS_InlineOnly) {
312 // Just checking TheLine->Level != 0 is not enough, because it
313 // provokes treating functions inside indented namespaces as short.
314 if (Style.isJavaScript() && TheLine->Last->is(TT_FunctionLBrace))
315 return true;
316
317 if (TheLine->Level != 0) {
318 if (!PreviousLine)
319 return false;
320
321 // TODO: Use IndentTracker to avoid loop?
322 // Find the last line with lower level.
323 const AnnotatedLine *Line = nullptr;
324 for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
325 assert(*J)(static_cast <bool> (*J) ? void (0) : __assert_fail ("*J"
, "clang/lib/Format/UnwrappedLineFormatter.cpp", 325, __extension__
__PRETTY_FUNCTION__))
;
326 if (!(*J)->InPPDirective && !(*J)->isComment() &&
327 (*J)->Level < TheLine->Level) {
328 Line = *J;
329 break;
330 }
331 }
332
333 if (!Line)
334 return false;
335
336 // Check if the found line starts a record.
337 const FormatToken *LastNonComment = Line->Last;
338 assert(LastNonComment)(static_cast <bool> (LastNonComment) ? void (0) : __assert_fail
("LastNonComment", "clang/lib/Format/UnwrappedLineFormatter.cpp"
, 338, __extension__ __PRETTY_FUNCTION__))
;
339 if (LastNonComment->is(tok::comment)) {
340 LastNonComment = LastNonComment->getPreviousNonComment();
341 // There must be another token (usually `{`), because we chose a
342 // non-PPDirective and non-comment line that has a smaller level.
343 assert(LastNonComment)(static_cast <bool> (LastNonComment) ? void (0) : __assert_fail
("LastNonComment", "clang/lib/Format/UnwrappedLineFormatter.cpp"
, 343, __extension__ __PRETTY_FUNCTION__))
;
344 }
345 return isRecordLBrace(*LastNonComment);
346 }
347 }
348
349 return false;
350 };
351
352 bool MergeShortFunctions = ShouldMergeShortFunctions();
353
354 const FormatToken *FirstNonComment = TheLine->First;
355 if (FirstNonComment->is(tok::comment)) {
356 FirstNonComment = FirstNonComment->getNextNonComment();
357 if (!FirstNonComment)
358 return 0;
359 }
360 // FIXME: There are probably cases where we should use FirstNonComment
361 // instead of TheLine->First.
362
363 if (Style.CompactNamespaces) {
364 if (const auto *NSToken = TheLine->First->getNamespaceToken()) {
365 int J = 1;
366 assert(TheLine->MatchingClosingBlockLineIndex > 0)(static_cast <bool> (TheLine->MatchingClosingBlockLineIndex
> 0) ? void (0) : __assert_fail ("TheLine->MatchingClosingBlockLineIndex > 0"
, "clang/lib/Format/UnwrappedLineFormatter.cpp", 366, __extension__
__PRETTY_FUNCTION__))
;
367 for (auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1;
368 I + J != E && NSToken->TokenText == getNamespaceTokenText(I[J]) &&
369 ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex &&
370 I[J]->Last->TotalLength < Limit;
371 ++J, --ClosingLineIndex) {
372 Limit -= I[J]->Last->TotalLength;
373
374 // Reduce indent level for bodies of namespaces which were compacted,
375 // but only if their content was indented in the first place.
376 auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1;
377 auto OutdentBy = I[J]->Level - TheLine->Level;
378 for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine;
379 ++CompactedLine) {
380 if (!(*CompactedLine)->InPPDirective)
381 (*CompactedLine)->Level -= OutdentBy;
382 }
383 }
384 return J - 1;
385 }
386
387 if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
388 int i = 0;
389 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
390 for (; I + 1 + i != E &&
391 nsToken->TokenText ==
392 getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
393 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
394 i++, --openingLine) {
395 // No space between consecutive braces.
396 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
397
398 // Indent like the outer-most namespace.
399 IndentTracker.nextLine(*I[i + 1]);
400 }
401 return i;
402 }
403 }
404
405 // Try to merge a function block with left brace unwrapped.
406 if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First != TheLine->Last)
407 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
408 // Try to merge a control statement block with left brace unwrapped.
409 if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
410 FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
411 TT_ForEachMacro)) {
412 return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
413 ? tryMergeSimpleBlock(I, E, Limit)
414 : 0;
415 }
416 // Try to merge a control statement block with left brace wrapped.
417 if (NextLine.First->is(tok::l_brace)) {
418 if ((TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
419 tok::kw_for, tok::kw_switch, tok::kw_try,
420 tok::kw_do, TT_ForEachMacro) ||
421 (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
422 TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
423 Style.BraceWrapping.AfterControlStatement ==
424 FormatStyle::BWACS_MultiLine) {
425 // If possible, merge the next line's wrapped left brace with the
426 // current line. Otherwise, leave it on the next line, as this is a
427 // multi-line control statement.
428 return (Style.ColumnLimit == 0 || TheLine->Level * Style.IndentWidth +
429 TheLine->Last->TotalLength <=
430 Style.ColumnLimit)
431 ? 1
432 : 0;
433 }
434 if (TheLine->First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
435 tok::kw_for, TT_ForEachMacro)) {
436 return (Style.BraceWrapping.AfterControlStatement ==
437 FormatStyle::BWACS_Always)
438 ? tryMergeSimpleBlock(I, E, Limit)
439 : 0;
440 }
441 if (TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) &&
442 Style.BraceWrapping.AfterControlStatement ==
443 FormatStyle::BWACS_MultiLine) {
444 // This case if different from the upper BWACS_MultiLine processing
445 // in that a preceding r_brace is not on the same line as else/catch
446 // most likely because of BeforeElse/BeforeCatch set to true.
447 // If the line length doesn't fit ColumnLimit, leave l_brace on the
448 // next line to respect the BWACS_MultiLine.
449 return (Style.ColumnLimit == 0 ||
450 TheLine->Last->TotalLength <= Style.ColumnLimit)
451 ? 1
452 : 0;
453 }
454 }
455 if (PreviousLine && TheLine->First->is(tok::l_brace)) {
456 switch (PreviousLine->First->Tok.getKind()) {
457 case tok::at:
458 // Don't merge block with left brace wrapped after ObjC special blocks.
459 if (PreviousLine->First->Next) {
460 tok::ObjCKeywordKind kwId =
461 PreviousLine->First->Next->Tok.getObjCKeywordID();
462 if (kwId == tok::objc_autoreleasepool ||
463 kwId == tok::objc_synchronized) {
464 return 0;
465 }
466 }
467 break;
468
469 case tok::kw_case:
470 case tok::kw_default:
471 // Don't merge block with left brace wrapped after case labels.
472 return 0;
473
474 default:
475 break;
476 }
477 }
478
479 // Don't merge an empty template class or struct if SplitEmptyRecords
480 // is defined.
481 if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord &&
482 TheLine->Last->is(tok::l_brace) && PreviousLine->Last) {
483 const FormatToken *Previous = PreviousLine->Last;
484 if (Previous) {
485 if (Previous->is(tok::comment))
486 Previous = Previous->getPreviousNonComment();
487 if (Previous) {
488 if (Previous->is(tok::greater) && !PreviousLine->InPPDirective)
489 return 0;
490 if (Previous->is(tok::identifier)) {
491 const FormatToken *PreviousPrevious =
492 Previous->getPreviousNonComment();
493 if (PreviousPrevious &&
494 PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) {
495 return 0;
496 }
497 }
498 }
499 }
500 }
501
502 if (TheLine->Last->is(tok::l_brace)) {
503 bool ShouldMerge = false;
504 // Try to merge records.
505 if (TheLine->Last->is(TT_EnumLBrace)) {
506 ShouldMerge = Style.AllowShortEnumsOnASingleLine;
507 } else if (TheLine->Last->isOneOf(TT_ClassLBrace, TT_StructLBrace)) {
508 // NOTE: We use AfterClass (whereas AfterStruct exists) for both classes
509 // and structs, but it seems that wrapping is still handled correctly
510 // elsewhere.
511 ShouldMerge = !Style.BraceWrapping.AfterClass ||
512 (NextLine.First->is(tok::r_brace) &&
513 !Style.BraceWrapping.SplitEmptyRecord);
514 } if(TheLine->InPPDirective ||
515 !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
516 tok::kw_struct)) {
517 // Try to merge a block with left brace unwrapped that wasn't yet
518 // covered.
519 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
520 (NextLine.First->is(tok::r_brace) &&
521 !Style.BraceWrapping.SplitEmptyFunction);
522 }
523 return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0;
524 }
525
526 // Try to merge a function block with left brace wrapped.
527 if (NextLine.First->is(TT_FunctionLBrace) &&
528 Style.BraceWrapping.AfterFunction) {
529 if (NextLine.Last->is(TT_LineComment))
530 return 0;
531
532 // Check for Limit <= 2 to account for the " {".
533 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
534 return 0;
535 Limit -= 2;
536
537 unsigned MergedLines = 0;
538 if (MergeShortFunctions ||
539 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
540 NextLine.First == NextLine.Last && I + 2 != E &&
541 I[2]->First->is(tok::r_brace))) {
542 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
543 // If we managed to merge the block, count the function header, which is
544 // on a separate line.
545 if (MergedLines > 0)
546 ++MergedLines;
547 }
548 return MergedLines;
549 }
550 auto IsElseLine = [&TheLine]() -> bool {
551 const FormatToken *First = TheLine->First;
552 if (First->is(tok::kw_else))
553 return true;
554
555 return First->is(tok::r_brace) && First->Next &&
556 First->Next->is(tok::kw_else);
557 };
558 if (TheLine->First->is(tok::kw_if) ||
559 (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine ==
560 FormatStyle::SIS_AllIfsAndElse))) {
561 return Style.AllowShortIfStatementsOnASingleLine
562 ? tryMergeSimpleControlStatement(I, E, Limit)
563 : 0;
564 }
565 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while, tok::kw_do,
566 TT_ForEachMacro)) {
567 return Style.AllowShortLoopsOnASingleLine
568 ? tryMergeSimpleControlStatement(I, E, Limit)
569 : 0;
570 }
571 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
572 return Style.AllowShortCaseLabelsOnASingleLine
573 ? tryMergeShortCaseLabels(I, E, Limit)
574 : 0;
575 }
576 if (TheLine->InPPDirective &&
577 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
578 return tryMergeSimplePPDirective(I, E, Limit);
579 }
580 return 0;
581 }
582
583 unsigned
584 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
585 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
586 unsigned Limit) {
587 if (Limit == 0)
588 return 0;
589 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
590 return 0;
591 if (1 + I[1]->Last->TotalLength > Limit)
592 return 0;
593 return 1;
594 }
595
596 unsigned tryMergeSimpleControlStatement(
597 SmallVectorImpl<AnnotatedLine *>::const_iterator I,
598 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
599 if (Limit == 0)
600 return 0;
601 if (Style.BraceWrapping.AfterControlStatement ==
602 FormatStyle::BWACS_Always &&
603 I[1]->First->is(tok::l_brace) &&
604 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) {
605 return 0;
606 }
607 if (I[1]->InPPDirective != (*I)->InPPDirective ||
608 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
609 return 0;
610 }
611 Limit = limitConsideringMacros(I + 1, E, Limit);
612 AnnotatedLine &Line = **I;
613 if (!Line.First->is(tok::kw_do) && !Line.First->is(tok::kw_else) &&
614 !Line.Last->is(tok::kw_else) && Line.Last->isNot(tok::r_paren)) {
615 return 0;
616 }
617 // Only merge `do while` if `do` is the only statement on the line.
618 if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do))
619 return 0;
620 if (1 + I[1]->Last->TotalLength > Limit)
621 return 0;
622 // Don't merge with loops, ifs, a single semicolon or a line comment.
623 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
624 TT_ForEachMacro, TT_LineComment)) {
625 return 0;
626 }
627 // Only inline simple if's (no nested if or else), unless specified
628 if (Style.AllowShortIfStatementsOnASingleLine ==
629 FormatStyle::SIS_WithoutElse) {
630 if (I + 2 != E && Line.startsWith(tok::kw_if) &&
631 I[2]->First->is(tok::kw_else)) {
632 return 0;
633 }
634 }
635 return 1;
636 }
637
638 unsigned
639 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
640 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
641 unsigned Limit) {
642 if (Limit == 0 || I + 1 == E ||
643 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) {
644 return 0;
645 }
646 if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
647 return 0;
648 unsigned NumStmts = 0;
649 unsigned Length = 0;
650 bool EndsWithComment = false;
651 bool InPPDirective = I[0]->InPPDirective;
652 bool InMacroBody = I[0]->InMacroBody;
653 const unsigned Level = I[0]->Level;
654 for (; NumStmts < 3; ++NumStmts) {
655 if (I + 1 + NumStmts == E)
656 break;
657 const AnnotatedLine *Line = I[1 + NumStmts];
658 if (Line->InPPDirective != InPPDirective)
659 break;
660 if (Line->InMacroBody != InMacroBody)
661 break;
662 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
663 break;
664 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
665 tok::kw_while) ||
666 EndsWithComment) {
667 return 0;
668 }
669 if (Line->First->is(tok::comment)) {
670 if (Level != Line->Level)
671 return 0;
672 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
673 for (; J != E; ++J) {
674 Line = *J;
675 if (Line->InPPDirective != InPPDirective)
676 break;
677 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
678 break;
679 if (Line->First->isNot(tok::comment) || Level != Line->Level)
680 return 0;
681 }
682 break;
683 }
684 if (Line->Last->is(tok::comment))
685 EndsWithComment = true;
686 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
687 }
688 if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
689 return 0;
690 return NumStmts;
691 }
692
693 unsigned
694 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
695 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
696 unsigned Limit) {
697 // Don't merge with a preprocessor directive.
698 if (I[1]->Type == LT_PreprocessorDirective)
699 return 0;
700
701 AnnotatedLine &Line = **I;
702
703 // Don't merge ObjC @ keywords and methods.
704 // FIXME: If an option to allow short exception handling clauses on a single
705 // line is added, change this to not return for @try and friends.
706 if (Style.Language != FormatStyle::LK_Java &&
707 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) {
708 return 0;
709 }
710
711 // Check that the current line allows merging. This depends on whether we
712 // are in a control flow statements as well as several style flags.
713 if (Line.First->is(tok::kw_case) ||
714 (Line.First->Next && Line.First->Next->is(tok::kw_else))) {
715 return 0;
716 }
717 // default: in switch statement
718 if (Line.First->is(tok::kw_default)) {
719 const FormatToken *Tok = Line.First->getNextNonComment();
720 if (Tok && Tok->is(tok::colon))
721 return 0;
722 }
723
724 auto IsCtrlStmt = [](const auto &Line) {
725 return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while,
726 tok::kw_do, tok::kw_for, TT_ForEachMacro);
727 };
728
729 const bool IsSplitBlock =
730 Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never ||
731 (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty &&
732 I[1]->First->isNot(tok::r_brace));
733
734 if (IsCtrlStmt(Line) ||
735 Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
736 tok::kw___finally, tok::r_brace,
737 Keywords.kw___except)) {
738 if (IsSplitBlock)
739 return 0;
740 // Don't merge when we can't except the case when
741 // the control statement block is empty
742 if (!Style.AllowShortIfStatementsOnASingleLine &&
743 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
744 !Style.BraceWrapping.AfterControlStatement &&
745 !I[1]->First->is(tok::r_brace)) {
746 return 0;
747 }
748 if (!Style.AllowShortIfStatementsOnASingleLine &&
749 Line.First->isOneOf(tok::kw_if, tok::kw_else) &&
750 Style.BraceWrapping.AfterControlStatement ==
751 FormatStyle::BWACS_Always &&
752 I + 2 != E && !I[2]->First->is(tok::r_brace)) {
753 return 0;
754 }
755 if (!Style.AllowShortLoopsOnASingleLine &&
756 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
757 TT_ForEachMacro) &&
758 !Style.BraceWrapping.AfterControlStatement &&
759 !I[1]->First->is(tok::r_brace)) {
760 return 0;
761 }
762 if (!Style.AllowShortLoopsOnASingleLine &&
763 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for,
764 TT_ForEachMacro) &&
765 Style.BraceWrapping.AfterControlStatement ==
766 FormatStyle::BWACS_Always &&
767 I + 2 != E && !I[2]->First->is(tok::r_brace)) {
768 return 0;
769 }
770 // FIXME: Consider an option to allow short exception handling clauses on
771 // a single line.
772 // FIXME: This isn't covered by tests.
773 // FIXME: For catch, __except, __finally the first token on the line
774 // is '}', so this isn't correct here.
775 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
776 Keywords.kw___except, tok::kw___finally)) {
777 return 0;
778 }
779 }
780
781 if (Line.Last->is(tok::l_brace)) {
782 if (IsSplitBlock && Line.First == Line.Last &&
783 I > AnnotatedLines.begin() &&
784 (I[-1]->endsWith(tok::kw_else) || IsCtrlStmt(*I[-1]))) {
785 return 0;
786 }
787 FormatToken *Tok = I[1]->First;
788 auto ShouldMerge = [Tok]() {
789 if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
790 return false;
791 const FormatToken *Next = Tok->getNextNonComment();
792 return !Next || Next->is(tok::semi);
793 };
794
795 if (ShouldMerge()) {
796 // We merge empty blocks even if the line exceeds the column limit.
797 Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
798 Tok->CanBreakBefore = true;
799 return 1;
800 } else if (Limit != 0 && !Line.startsWithNamespace() &&
801 !startsExternCBlock(Line)) {
802 // We don't merge short records.
803 if (isRecordLBrace(*Line.Last))
804 return 0;
805
806 // Check that we still have three lines and they fit into the limit.
807 if (I + 2 == E || I[2]->Type == LT_Invalid)
808 return 0;
809 Limit = limitConsideringMacros(I + 2, E, Limit);
810
811 if (!nextTwoLinesFitInto(I, Limit))
812 return 0;
813
814 // Second, check that the next line does not contain any braces - if it
815 // does, readability declines when putting it into a single line.
816 if (I[1]->Last->is(TT_LineComment))
817 return 0;
818 do {
819 if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
820 return 0;
821 Tok = Tok->Next;
822 } while (Tok);
823
824 // Last, check that the third line starts with a closing brace.
825 Tok = I[2]->First;
826 if (Tok->isNot(tok::r_brace))
827 return 0;
828
829 // Don't merge "if (a) { .. } else {".
830 if (Tok->Next && Tok->Next->is(tok::kw_else))
831 return 0;
832
833 // Don't merge a trailing multi-line control statement block like:
834 // } else if (foo &&
835 // bar)
836 // { <-- current Line
837 // baz();
838 // }
839 if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) &&
840 Style.BraceWrapping.AfterControlStatement ==
841 FormatStyle::BWACS_MultiLine) {
842 return 0;
843 }
844
845 return 2;
846 }
847 } else if (I[1]->First->is(tok::l_brace)) {
848 if (I[1]->Last->is(TT_LineComment))
849 return 0;
850
851 // Check for Limit <= 2 to account for the " {".
852 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
853 return 0;
854 Limit -= 2;
855 unsigned MergedLines = 0;
856 if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
857 (I[1]->First == I[1]->Last && I + 2 != E &&
858 I[2]->First->is(tok::r_brace))) {
859 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
860 // If we managed to merge the block, count the statement header, which
861 // is on a separate line.
862 if (MergedLines > 0)
863 ++MergedLines;
864 }
865 return MergedLines;
866 }
867 return 0;
868 }
869
870 /// Returns the modified column limit for \p I if it is inside a macro and
871 /// needs a trailing '\'.
872 unsigned
873 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
874 SmallVectorImpl<AnnotatedLine *>::const_iterator E,
875 unsigned Limit) {
876 if (I[0]->InPPDirective && I + 1 != E &&
877 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
878 return Limit < 2 ? 0 : Limit - 2;
879 }
880 return Limit;
881 }
882
883 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
884 unsigned Limit) {
885 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
886 return false;
887 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
888 }
889
890 bool containsMustBreak(const AnnotatedLine *Line) {
891 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next)
892 if (Tok->MustBreakBefore)
893 return true;
894 return false;
895 }
896
897 void join(AnnotatedLine &A, const AnnotatedLine &B) {
898 assert(!A.Last->Next)(static_cast <bool> (!A.Last->Next) ? void (0) : __assert_fail
("!A.Last->Next", "clang/lib/Format/UnwrappedLineFormatter.cpp"
, 898, __extension__ __PRETTY_FUNCTION__))
;
899 assert(!B.First->Previous)(static_cast <bool> (!B.First->Previous) ? void (0) :
__assert_fail ("!B.First->Previous", "clang/lib/Format/UnwrappedLineFormatter.cpp"
, 899, __extension__ __PRETTY_FUNCTION__))
;
900 if (B.Affected)
901 A.Affected = true;
902 A.Last->Next = B.First;
903 B.First->Previous = A.Last;
904 B.First->CanBreakBefore = true;
905 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
906 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
907 Tok->TotalLength += LengthA;
908 A.Last = Tok;
909 }
910 }
911
912 const FormatStyle &Style;
913 const AdditionalKeywords &Keywords;
914 const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
915
916 SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
917 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
918};
919
920static void markFinalized(FormatToken *Tok) {
921 for (; Tok; Tok = Tok->Next) {
922 if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
923 // In the first pass we format all macro arguments in the expanded token
924 // stream. Instead of finalizing the macro arguments, we mark that they
925 // will be modified as unexpanded arguments (as part of the macro call
926 // formatting) in the next pass.
927 Tok->MacroCtx->Role = MR_UnexpandedArg;
928 // Reset whether spaces are required before this token, as that is context
929 // dependent, and that context may change when formatting the macro call.
930 // For example, given M(x) -> 2 * x, and the macro call M(var),
931 // the token 'var' will have SpacesRequiredBefore = 1 after being
932 // formatted as part of the expanded macro, but SpacesRequiredBefore = 0
933 // for its position within the macro call.
934 Tok->SpacesRequiredBefore = 0;
935 } else {
936 Tok->Finalized = true;
937 }
938 }
939}
940
941#ifndef NDEBUG
942static void printLineState(const LineState &State) {
943 llvm::dbgs() << "State: ";
944 for (const ParenState &P : State.Stack) {
945 llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
946 << P.LastSpace << "|" << P.NestedBlockIndent << " ";
947 }
948 llvm::dbgs() << State.NextToken->TokenText << "\n";
949}
950#endif
951
952/// Base class for classes that format one \c AnnotatedLine.
953class LineFormatter {
954public:
955 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
956 const FormatStyle &Style,
957 UnwrappedLineFormatter *BlockFormatter)
958 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
959 BlockFormatter(BlockFormatter) {}
960 virtual ~LineFormatter() {}
961
962 /// Formats an \c AnnotatedLine and returns the penalty.
963 ///
964 /// If \p DryRun is \c false, directly applies the changes.
965 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
966 unsigned FirstStartColumn, bool DryRun) = 0;
967
968protected:
969 /// If the \p State's next token is an r_brace closing a nested block,
970 /// format the nested block before it.
971 ///
972 /// Returns \c true if all children could be placed successfully and adapts
973 /// \p Penalty as well as \p State. If \p DryRun is false, also directly
974 /// creates changes using \c Whitespaces.
975 ///
976 /// The crucial idea here is that children always get formatted upon
977 /// encountering the closing brace right after the nested block. Now, if we
978 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
979 /// \c false), the entire block has to be kept on the same line (which is only
980 /// possible if it fits on the line, only contains a single statement, etc.
981 ///
982 /// If \p NewLine is true, we format the nested block on separate lines, i.e.
983 /// break after the "{", format all lines with correct indentation and the put
984 /// the closing "}" on yet another new line.
985 ///
986 /// This enables us to keep the simple structure of the
987 /// \c UnwrappedLineFormatter, where we only have two options for each token:
988 /// break or don't break.
989 bool formatChildren(LineState &State, bool NewLine, bool DryRun,
990 unsigned &Penalty) {
991 const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
1
'LBrace' initialized here
992 bool HasLBrace = LBrace && LBrace->is(tok::l_brace) && LBrace->is(BK_Block);
2
Assuming 'LBrace' is null
993 FormatToken &Previous = *State.NextToken->Previous;
994 if (Previous.Children.size() == 0 || (!HasLBrace
3.1
'HasLBrace' is false
&& !LBrace->MacroParent)) {
3
Assuming the condition is false
4
Access to field 'MacroParent' results in a dereference of a null pointer (loaded from variable 'LBrace')
995 // The previous token does not open a block. Nothing to do. We don't
996 // assert so that we can simply call this function for all tokens.
997 return true;
998 }
999
1000 if (NewLine || Previous.MacroParent) {
1001 const ParenState &P = State.Stack.back();
1002
1003 int AdditionalIndent =
1004 P.Indent - Previous.Children[0]->Level * Style.IndentWidth;
1005
1006 if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
1007 P.NestedBlockIndent == P.LastSpace) {
1008 if (State.NextToken->MatchingParen &&
1009 State.NextToken->MatchingParen->is(TT_LambdaLBrace)) {
1010 State.Stack.pop_back();
1011 }
1012 if (LBrace->is(TT_LambdaLBrace))
1013 AdditionalIndent = 0;
1014 }
1015
1016 Penalty +=
1017 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
1018 /*FixBadIndentation=*/true);
1019 return true;
1020 }
1021
1022 if (Previous.Children[0]->First->MustBreakBefore)
1023 return false;
1024
1025 // Cannot merge into one line if this line ends on a comment.
1026 if (Previous.is(tok::comment))
1027 return false;
1028
1029 // Cannot merge multiple statements into a single line.
1030 if (Previous.Children.size() > 1)
1031 return false;
1032
1033 const AnnotatedLine *Child = Previous.Children[0];
1034 // We can't put the closing "}" on a line with a trailing comment.
1035 if (Child->Last->isTrailingComment())
1036 return false;
1037
1038 // If the child line exceeds the column limit, we wouldn't want to merge it.
1039 // We add +2 for the trailing " }".
1040 if (Style.ColumnLimit > 0 &&
1041 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) {
1042 return false;
1043 }
1044
1045 if (!DryRun) {
1046 Whitespaces->replaceWhitespace(
1047 *Child->First, /*Newlines=*/0, /*Spaces=*/1,
1048 /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false,
1049 State.Line->InPPDirective);
1050 }
1051 Penalty +=
1052 formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1053
1054 State.Column += 1 + Child->Last->TotalLength;
1055 return true;
1056 }
1057
1058 ContinuationIndenter *Indenter;
1059
1060private:
1061 WhitespaceManager *Whitespaces;
1062 const FormatStyle &Style;
1063 UnwrappedLineFormatter *BlockFormatter;
1064};
1065
1066/// Formatter that keeps the existing line breaks.
1067class NoColumnLimitLineFormatter : public LineFormatter {
1068public:
1069 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
1070 WhitespaceManager *Whitespaces,
1071 const FormatStyle &Style,
1072 UnwrappedLineFormatter *BlockFormatter)
1073 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1074
1075 /// Formats the line, simply keeping all of the input's line breaking
1076 /// decisions.
1077 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1078 unsigned FirstStartColumn, bool DryRun) override {
1079 assert(!DryRun)(static_cast <bool> (!DryRun) ? void (0) : __assert_fail
("!DryRun", "clang/lib/Format/UnwrappedLineFormatter.cpp", 1079
, __extension__ __PRETTY_FUNCTION__))
;
1080 LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
1081 &Line, /*DryRun=*/false);
1082 while (State.NextToken) {
1083 bool Newline =
1084 Indenter->mustBreak(State) ||
1085 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
1086 unsigned Penalty = 0;
1087 formatChildren(State, Newline, /*DryRun=*/false, Penalty);
1088 Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
1089 }
1090 return 0;
1091 }
1092};
1093
1094/// Formatter that puts all tokens into a single line without breaks.
1095class NoLineBreakFormatter : public LineFormatter {
1096public:
1097 NoLineBreakFormatter(ContinuationIndenter *Indenter,
1098 WhitespaceManager *Whitespaces, const FormatStyle &Style,
1099 UnwrappedLineFormatter *BlockFormatter)
1100 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1101
1102 /// Puts all tokens into a single line.
1103 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1104 unsigned FirstStartColumn, bool DryRun) override {
1105 unsigned Penalty = 0;
1106 LineState State =
1107 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1108 while (State.NextToken) {
1109 formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
1110 Indenter->addTokenToState(
1111 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
1112 }
1113 return Penalty;
1114 }
1115};
1116
1117/// Finds the best way to break lines.
1118class OptimizingLineFormatter : public LineFormatter {
1119public:
1120 OptimizingLineFormatter(ContinuationIndenter *Indenter,
1121 WhitespaceManager *Whitespaces,
1122 const FormatStyle &Style,
1123 UnwrappedLineFormatter *BlockFormatter)
1124 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
1125
1126 /// Formats the line by finding the best line breaks with line lengths
1127 /// below the column limit.
1128 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
1129 unsigned FirstStartColumn, bool DryRun) override {
1130 LineState State =
1131 Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
1132
1133 // If the ObjC method declaration does not fit on a line, we should format
1134 // it with one arg per line.
1135 if (State.Line->Type == LT_ObjCMethodDecl)
1136 State.Stack.back().BreakBeforeParameter = true;
1137
1138 // Find best solution in solution space.
1139 return analyzeSolutionSpace(State, DryRun);
1140 }
1141
1142private:
1143 struct CompareLineStatePointers {
1144 bool operator()(LineState *obj1, LineState *obj2) const {
1145 return *obj1 < *obj2;
1146 }
1147 };
1148
1149 /// A pair of <penalty, count> that is used to prioritize the BFS on.
1150 ///
1151 /// In case of equal penalties, we want to prefer states that were inserted
1152 /// first. During state generation we make sure that we insert states first
1153 /// that break the line as late as possible.
1154 typedef std::pair<unsigned, unsigned> OrderedPenalty;
1155
1156 /// An edge in the solution space from \c Previous->State to \c State,
1157 /// inserting a newline dependent on the \c NewLine.
1158 struct StateNode {
1159 StateNode(const LineState &State, bool NewLine, StateNode *Previous)
1160 : State(State), NewLine(NewLine), Previous(Previous) {}
1161 LineState State;
1162 bool NewLine;
1163 StateNode *Previous;
1164 };
1165
1166 /// An item in the prioritized BFS search queue. The \c StateNode's
1167 /// \c State has the given \c OrderedPenalty.
1168 typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
1169
1170 /// The BFS queue type.
1171 typedef std::priority_queue<QueueItem, SmallVector<QueueItem>,
1172 std::greater<QueueItem>>
1173 QueueType;
1174
1175 /// Analyze the entire solution space starting from \p InitialState.
1176 ///
1177 /// This implements a variant of Dijkstra's algorithm on the graph that spans
1178 /// the solution space (\c LineStates are the nodes). The algorithm tries to
1179 /// find the shortest path (the one with lowest penalty) from \p InitialState
1180 /// to a state where all tokens are placed. Returns the penalty.
1181 ///
1182 /// If \p DryRun is \c false, directly applies the changes.
1183 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
1184 std::set<LineState *, CompareLineStatePointers> Seen;
1185
1186 // Increasing count of \c StateNode items we have created. This is used to
1187 // create a deterministic order independent of the container.
1188 unsigned Count = 0;
1189 QueueType Queue;
1190
1191 // Insert start element into queue.
1192 StateNode *RootNode =
1193 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
1194 Queue.push(QueueItem(OrderedPenalty(0, Count), RootNode));
1195 ++Count;
1196
1197 unsigned Penalty = 0;
1198
1199 // While not empty, take first element and follow edges.
1200 while (!Queue.empty()) {
1201 // Quit if we still haven't found a solution by now.
1202 if (Count > 25000000)
1203 return 0;
1204
1205 Penalty = Queue.top().first.first;
1206 StateNode *Node = Queue.top().second;
1207 if (!Node->State.NextToken) {
1208 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "\n---\nPenalty for line: "
<< Penalty << "\n"; } } while (false)
1209 << "\n---\nPenalty for line: " << Penalty << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "\n---\nPenalty for line: "
<< Penalty << "\n"; } } while (false)
;
1210 break;
1211 }
1212 Queue.pop();
1213
1214 // Cut off the analysis of certain solutions if the analysis gets too
1215 // complex. See description of IgnoreStackForComparison.
1216 if (Count > 50000)
1217 Node->State.IgnoreStackForComparison = true;
1218
1219 if (!Seen.insert(&Node->State).second) {
1220 // State already examined with lower penalty.
1221 continue;
1222 }
1223
1224 FormatDecision LastFormat = Node->State.NextToken->getDecision();
1225 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
1226 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
1227 if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
1228 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
1229 }
1230
1231 if (Queue.empty()) {
1232 // We were unable to find a solution, do nothing.
1233 // FIXME: Add diagnostic?
1234 LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "Could not find a solution.\n"
; } } while (false)
;
1235 return 0;
1236 }
1237
1238 // Reconstruct the solution.
1239 if (!DryRun)
1240 reconstructPath(InitialState, Queue.top().second);
1241
1242 LLVM_DEBUG(llvm::dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "Total number of analyzed states: "
<< Count << "\n"; } } while (false)
1243 << "Total number of analyzed states: " << Count << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "Total number of analyzed states: "
<< Count << "\n"; } } while (false)
;
1244 LLVM_DEBUG(llvm::dbgs() << "---\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { llvm::dbgs() << "---\n"; } } while
(false)
;
1245
1246 return Penalty;
1247 }
1248
1249 /// Add the following state to the analysis queue \c Queue.
1250 ///
1251 /// Assume the current state is \p PreviousNode and has been reached with a
1252 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
1253 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
1254 bool NewLine, unsigned *Count, QueueType *Queue) {
1255 if (NewLine && !Indenter->canBreak(PreviousNode->State))
1256 return;
1257 if (!NewLine && Indenter->mustBreak(PreviousNode->State))
1258 return;
1259
1260 StateNode *Node = new (Allocator.Allocate())
1261 StateNode(PreviousNode->State, NewLine, PreviousNode);
1262 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
1263 return;
1264
1265 Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
1266
1267 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
1268 ++(*Count);
1269 }
1270
1271 /// Applies the best formatting by reconstructing the path in the
1272 /// solution space that leads to \c Best.
1273 void reconstructPath(LineState &State, StateNode *Best) {
1274 llvm::SmallVector<StateNode *> Path;
1275 // We do not need a break before the initial token.
1276 while (Best->Previous) {
1277 Path.push_back(Best);
1278 Best = Best->Previous;
1279 }
1280 for (const auto &Node : llvm::reverse(Path)) {
1281 unsigned Penalty = 0;
1282 formatChildren(State, Node->NewLine, /*DryRun=*/false, Penalty);
1283 Penalty += Indenter->addTokenToState(State, Node->NewLine, false);
1284
1285 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1286 printLineState(Node->Previous->State);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1287 if (Node->NewLine) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1288 llvm::dbgs() << "Penalty for placing "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1289 << Node->Previous->State.NextToken->Tok.getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1290 << " on a new line: " << Penalty << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1291 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
1292 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("format-formatter")) { { printLineState(Node->Previous->
State); if (Node->NewLine) { llvm::dbgs() << "Penalty for placing "
<< Node->Previous->State.NextToken->Tok.getName
() << " on a new line: " << Penalty << "\n"
; } }; } } while (false)
;
1293 }
1294 }
1295
1296 llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
1297};
1298
1299} // anonymous namespace
1300
1301unsigned UnwrappedLineFormatter::format(
1302 const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
1303 int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
1304 unsigned NextStartColumn, unsigned LastStartColumn) {
1305 LineJoiner Joiner(Style, Keywords, Lines);
1306
1307 // Try to look up already computed penalty in DryRun-mode.
1308 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
1309 &Lines, AdditionalIndent);
1310 auto CacheIt = PenaltyCache.find(CacheKey);
1311 if (DryRun && CacheIt != PenaltyCache.end())
1312 return CacheIt->second;
1313
1314 assert(!Lines.empty())(static_cast <bool> (!Lines.empty()) ? void (0) : __assert_fail
("!Lines.empty()", "clang/lib/Format/UnwrappedLineFormatter.cpp"
, 1314, __extension__ __PRETTY_FUNCTION__))
;
1315 unsigned Penalty = 0;
1316 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
1317 AdditionalIndent);
1318 const AnnotatedLine *PrevPrevLine = nullptr;
1319 const AnnotatedLine *PreviousLine = nullptr;
1320 const AnnotatedLine *NextLine = nullptr;
1321
1322 // The minimum level of consecutive lines that have been formatted.
1323 unsigned RangeMinLevel = UINT_MAX(2147483647 *2U +1U);
1324
1325 bool FirstLine = true;
1326 for (const AnnotatedLine *Line =
1327 Joiner.getNextMergedLine(DryRun, IndentTracker);
1328 Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine,
1329 FirstLine = false) {
1330 assert(Line->First)(static_cast <bool> (Line->First) ? void (0) : __assert_fail
("Line->First", "clang/lib/Format/UnwrappedLineFormatter.cpp"
, 1330, __extension__ __PRETTY_FUNCTION__))
;
1331 const AnnotatedLine &TheLine = *Line;
1332 unsigned Indent = IndentTracker.getIndent();
1333
1334 // We continue formatting unchanged lines to adjust their indent, e.g. if a
1335 // scope was added. However, we need to carefully stop doing this when we
1336 // exit the scope of affected lines to prevent indenting the entire
1337 // remaining file if it currently missing a closing brace.
1338 bool PreviousRBrace =
1339 PreviousLine && PreviousLine->startsWith(tok::r_brace);
1340 bool ContinueFormatting =
1341 TheLine.Level > RangeMinLevel ||
1342 (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
1343 !TheLine.startsWith(tok::r_brace));
1344
1345 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
1346 Indent != TheLine.First->OriginalColumn;
1347 bool ShouldFormat = TheLine.Affected || FixIndentation;
1348 // We cannot format this line; if the reason is that the line had a
1349 // parsing error, remember that.
1350 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
1351 Status->FormatComplete = false;
1352 Status->Line =
1353 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
1354 }
1355
1356 if (ShouldFormat && TheLine.Type != LT_Invalid) {
1357 if (!DryRun) {
1358 bool LastLine = TheLine.First->is(tok::eof);
1359 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, Indent,
1360 LastLine ? LastStartColumn : NextStartColumn + Indent);
1361 }
1362
1363 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1364 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
1365 bool FitsIntoOneLine =
1366 !TheLine.ContainsMacroCall &&
1367 (TheLine.Last->TotalLength + Indent <= ColumnLimit ||
1368 (TheLine.Type == LT_ImportStatement &&
1369 (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) ||
1370 (Style.isCSharp() &&
1371 TheLine.InPPDirective)); // don't split #regions in C#
1372 if (Style.ColumnLimit == 0) {
1373 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
1374 .formatLine(TheLine, NextStartColumn + Indent,
1375 FirstLine ? FirstStartColumn : 0, DryRun);
1376 } else if (FitsIntoOneLine) {
1377 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
1378 .formatLine(TheLine, NextStartColumn + Indent,
1379 FirstLine ? FirstStartColumn : 0, DryRun);
1380 } else {
1381 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
1382 .formatLine(TheLine, NextStartColumn + Indent,
1383 FirstLine ? FirstStartColumn : 0, DryRun);
1384 }
1385 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
1386 } else {
1387 // If no token in the current line is affected, we still need to format
1388 // affected children.
1389 if (TheLine.ChildrenAffected) {
1390 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
1391 if (!Tok->Children.empty())
1392 format(Tok->Children, DryRun);
1393 }
1394
1395 // Adapt following lines on the current indent level to the same level
1396 // unless the current \c AnnotatedLine is not at the beginning of a line.
1397 bool StartsNewLine =
1398 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
1399 if (StartsNewLine)
1400 IndentTracker.adjustToUnmodifiedLine(TheLine);
1401 if (!DryRun) {
1402 bool ReformatLeadingWhitespace =
1403 StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
1404 TheLine.LeadingEmptyLinesAffected);
1405 // Format the first token.
1406 if (ReformatLeadingWhitespace) {
1407 formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines,
1408 TheLine.First->OriginalColumn,
1409 TheLine.First->OriginalColumn);
1410 } else {
1411 Whitespaces->addUntouchableToken(*TheLine.First,
1412 TheLine.InPPDirective);
1413 }
1414
1415 // Notify the WhitespaceManager about the unchanged whitespace.
1416 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
1417 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
1418 }
1419 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
1420 RangeMinLevel = UINT_MAX(2147483647 *2U +1U);
1421 }
1422 if (!DryRun)
1423 markFinalized(TheLine.First);
1424 }
1425 PenaltyCache[CacheKey] = Penalty;
1426 return Penalty;
1427}
1428
1429void UnwrappedLineFormatter::formatFirstToken(
1430 const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
1431 const AnnotatedLine *PrevPrevLine,
1432 const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
1433 unsigned NewlineIndent) {
1434 FormatToken &RootToken = *Line.First;
1435 if (RootToken.is(tok::eof)) {
1436 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
1437 unsigned TokenIndent = Newlines ? NewlineIndent : 0;
1438 Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
1439 TokenIndent);
1440 return;
1441 }
1442 unsigned Newlines =
1443 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
1444 // Remove empty lines before "}" where applicable.
1445 if (RootToken.is(tok::r_brace) &&
1446 (!RootToken.Next ||
1447 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
1448 // Do not remove empty lines before namespace closing "}".
1449 !getNamespaceToken(&Line, Lines)) {
1450 Newlines = std::min(Newlines, 1u);
1451 }
1452 // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
1453 if (!PreviousLine && Line.Level > 0)
1454 Newlines = std::min(Newlines, 1u);
1455 if (Newlines == 0 && !RootToken.IsFirst)
1456 Newlines = 1;
1457 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
1458 Newlines = 0;
1459
1460 // Remove empty lines after "{".
1461 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
1462 PreviousLine->Last->is(tok::l_brace) &&
1463 !PreviousLine->startsWithNamespace() &&
1464 !(PrevPrevLine && PrevPrevLine->startsWithNamespace() &&
1465 PreviousLine->startsWith(tok::l_brace)) &&
1466 !startsExternCBlock(*PreviousLine)) {
1467 Newlines = 1;
1468 }
1469
1470 // Insert or remove empty line before access specifiers.
1471 if (PreviousLine && RootToken.isAccessSpecifier()) {
1472 switch (Style.EmptyLineBeforeAccessModifier) {
1473 case FormatStyle::ELBAMS_Never:
1474 if (Newlines > 1)
1475 Newlines = 1;
1476 break;
1477 case FormatStyle::ELBAMS_Leave:
1478 Newlines = std::max(RootToken.NewlinesBefore, 1u);
1479 break;
1480 case FormatStyle::ELBAMS_LogicalBlock:
1481 if (PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && Newlines <= 1)
1482 Newlines = 2;
1483 if (PreviousLine->First->isAccessSpecifier())
1484 Newlines = 1; // Previous is an access modifier remove all new lines.
1485 break;
1486 case FormatStyle::ELBAMS_Always: {
1487 const FormatToken *previousToken;
1488 if (PreviousLine->Last->is(tok::comment))
1489 previousToken = PreviousLine->Last->getPreviousNonComment();
1490 else
1491 previousToken = PreviousLine->Last;
1492 if ((!previousToken || !previousToken->is(tok::l_brace)) && Newlines <= 1)
1493 Newlines = 2;
1494 } break;
1495 }
1496 }
1497
1498 // Insert or remove empty line after access specifiers.
1499 if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
1500 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) {
1501 // EmptyLineBeforeAccessModifier is handling the case when two access
1502 // modifiers follow each other.
1503 if (!RootToken.isAccessSpecifier()) {
1504 switch (Style.EmptyLineAfterAccessModifier) {
1505 case FormatStyle::ELAAMS_Never:
1506 Newlines = 1;
1507 break;
1508 case FormatStyle::ELAAMS_Leave:
1509 Newlines = std::max(Newlines, 1u);
1510 break;
1511 case FormatStyle::ELAAMS_Always:
1512 if (RootToken.is(tok::r_brace)) // Do not add at end of class.
1513 Newlines = 1u;
1514 else
1515 Newlines = std::max(Newlines, 2u);
1516 break;
1517 }
1518 }
1519 }
1520
1521 if (Newlines)
1522 Indent = NewlineIndent;
1523
1524 // Preprocessor directives get indented before the hash only if specified. In
1525 // Javascript import statements are indented like normal statements.
1526 if (!Style.isJavaScript() &&
1527 Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1528 (Line.Type == LT_PreprocessorDirective ||
1529 Line.Type == LT_ImportStatement)) {
1530 Indent = 0;
1531 }
1532
1533 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
1534 /*IsAligned=*/false,
1535 Line.InPPDirective &&
1536 !RootToken.HasUnescapedNewline);
1537}
1538
1539unsigned
1540UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
1541 const AnnotatedLine *NextLine) const {
1542 // In preprocessor directives reserve two chars for trailing " \" if the
1543 // next line continues the preprocessor directive.
1544 bool ContinuesPPDirective =
1545 InPPDirective &&
1546 // If there is no next line, this is likely a child line and the parent
1547 // continues the preprocessor directive.
1548 (!NextLine ||
1549 (NextLine->InPPDirective &&
1550 // If there is an unescaped newline between this line and the next, the
1551 // next line starts a new preprocessor directive.
1552 !NextLine->First->HasUnescapedNewline));
1553 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
1554}
1555
1556} // namespace format
1557} // namespace clang