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