1277325Sdim//===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===// 2277325Sdim// 3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4353358Sdim// See https://llvm.org/LICENSE.txt for license information. 5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6277325Sdim// 7277325Sdim//===----------------------------------------------------------------------===// 8277325Sdim 9353358Sdim#include "UnwrappedLineFormatter.h" 10341825Sdim#include "NamespaceEndCommentsFixer.h" 11277325Sdim#include "WhitespaceManager.h" 12277325Sdim#include "llvm/Support/Debug.h" 13314564Sdim#include <queue> 14277325Sdim 15277325Sdim#define DEBUG_TYPE "format-formatter" 16277325Sdim 17277325Sdimnamespace clang { 18277325Sdimnamespace format { 19277325Sdim 20277325Sdimnamespace { 21277325Sdim 22277325Sdimbool startsExternCBlock(const AnnotatedLine &Line) { 23277325Sdim const FormatToken *Next = Line.First->getNextNonComment(); 24277325Sdim const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; 25288943Sdim return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() && 26277325Sdim NextNext && NextNext->is(tok::l_brace); 27277325Sdim} 28277325Sdim 29341825Sdim/// Tracks the indent level of \c AnnotatedLines across levels. 30288943Sdim/// 31288943Sdim/// \c nextLine must be called for each \c AnnotatedLine, after which \c 32288943Sdim/// getIndent() will return the indent for the last line \c nextLine was called 33288943Sdim/// with. 34288943Sdim/// If the line is not formatted (and thus the indent does not change), calling 35288943Sdim/// \c adjustToUnmodifiedLine after the call to \c nextLine will cause 36288943Sdim/// subsequent lines on the same level to be indented at the same level as the 37288943Sdim/// given line. 38288943Sdimclass LevelIndentTracker { 39288943Sdimpublic: 40288943Sdim LevelIndentTracker(const FormatStyle &Style, 41288943Sdim const AdditionalKeywords &Keywords, unsigned StartLevel, 42288943Sdim int AdditionalIndent) 43288943Sdim : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) { 44288943Sdim for (unsigned i = 0; i != StartLevel; ++i) 45288943Sdim IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); 46288943Sdim } 47288943Sdim 48341825Sdim /// Returns the indent for the current line. 49288943Sdim unsigned getIndent() const { return Indent; } 50288943Sdim 51341825Sdim /// Update the indent state given that \p Line is going to be formatted 52288943Sdim /// next. 53288943Sdim void nextLine(const AnnotatedLine &Line) { 54288943Sdim Offset = getIndentOffset(*Line.First); 55288943Sdim // Update the indent level cache size so that we can rely on it 56288943Sdim // having the right size in adjustToUnmodifiedline. 57288943Sdim while (IndentForLevel.size() <= Line.Level) 58288943Sdim IndentForLevel.push_back(-1); 59288943Sdim if (Line.InPPDirective) { 60288943Sdim Indent = Line.Level * Style.IndentWidth + AdditionalIndent; 61288943Sdim } else { 62288943Sdim IndentForLevel.resize(Line.Level + 1); 63288943Sdim Indent = getIndent(IndentForLevel, Line.Level); 64288943Sdim } 65288943Sdim if (static_cast<int>(Indent) + Offset >= 0) 66288943Sdim Indent += Offset; 67288943Sdim } 68288943Sdim 69341825Sdim /// Update the indent state given that \p Line indent should be 70321369Sdim /// skipped. 71321369Sdim void skipLine(const AnnotatedLine &Line) { 72321369Sdim while (IndentForLevel.size() <= Line.Level) 73321369Sdim IndentForLevel.push_back(Indent); 74321369Sdim } 75321369Sdim 76341825Sdim /// Update the level indent to adapt to the given \p Line. 77288943Sdim /// 78288943Sdim /// When a line is not formatted, we move the subsequent lines on the same 79288943Sdim /// level to the same indent. 80288943Sdim /// Note that \c nextLine must have been called before this method. 81288943Sdim void adjustToUnmodifiedLine(const AnnotatedLine &Line) { 82288943Sdim unsigned LevelIndent = Line.First->OriginalColumn; 83288943Sdim if (static_cast<int>(LevelIndent) - Offset >= 0) 84288943Sdim LevelIndent -= Offset; 85288943Sdim if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) && 86288943Sdim !Line.InPPDirective) 87288943Sdim IndentForLevel[Line.Level] = LevelIndent; 88288943Sdim } 89288943Sdim 90288943Sdimprivate: 91341825Sdim /// Get the offset of the line relatively to the level. 92288943Sdim /// 93288943Sdim /// For example, 'public:' labels in classes are offset by 1 or 2 94288943Sdim /// characters to the left from their level. 95288943Sdim int getIndentOffset(const FormatToken &RootToken) { 96288943Sdim if (Style.Language == FormatStyle::LK_Java || 97353358Sdim Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) 98288943Sdim return 0; 99288943Sdim if (RootToken.isAccessSpecifier(false) || 100288943Sdim RootToken.isObjCAccessSpecifier() || 101296417Sdim (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) && 102296417Sdim RootToken.Next && RootToken.Next->is(tok::colon))) 103288943Sdim return Style.AccessModifierOffset; 104288943Sdim return 0; 105288943Sdim } 106288943Sdim 107341825Sdim /// Get the indent of \p Level from \p IndentForLevel. 108288943Sdim /// 109288943Sdim /// \p IndentForLevel must contain the indent for the level \c l 110288943Sdim /// at \p IndentForLevel[l], or a value < 0 if the indent for 111288943Sdim /// that level is unknown. 112288943Sdim unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) { 113288943Sdim if (IndentForLevel[Level] != -1) 114288943Sdim return IndentForLevel[Level]; 115288943Sdim if (Level == 0) 116288943Sdim return 0; 117288943Sdim return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; 118288943Sdim } 119288943Sdim 120288943Sdim const FormatStyle &Style; 121288943Sdim const AdditionalKeywords &Keywords; 122288943Sdim const unsigned AdditionalIndent; 123288943Sdim 124341825Sdim /// The indent in characters for each level. 125288943Sdim std::vector<int> IndentForLevel; 126288943Sdim 127341825Sdim /// Offset of the current line relative to the indent level. 128288943Sdim /// 129288943Sdim /// For example, the 'public' keywords is often indented with a negative 130288943Sdim /// offset. 131288943Sdim int Offset = 0; 132288943Sdim 133341825Sdim /// The current line's indent. 134288943Sdim unsigned Indent = 0; 135288943Sdim}; 136288943Sdim 137353358Sdimconst FormatToken *getMatchingNamespaceToken( 138353358Sdim const AnnotatedLine *Line, 139353358Sdim const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 140321369Sdim if (!Line->startsWith(tok::r_brace)) 141353358Sdim return nullptr; 142321369Sdim size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; 143321369Sdim if (StartLineIndex == UnwrappedLine::kInvalidIndex) 144353358Sdim return nullptr; 145321369Sdim assert(StartLineIndex < AnnotatedLines.size()); 146353358Sdim return AnnotatedLines[StartLineIndex]->First->getNamespaceToken(); 147321369Sdim} 148321369Sdim 149353358SdimStringRef getNamespaceTokenText(const AnnotatedLine *Line) { 150353358Sdim const FormatToken *NamespaceToken = Line->First->getNamespaceToken(); 151353358Sdim return NamespaceToken ? NamespaceToken->TokenText : StringRef(); 152353358Sdim} 153353358Sdim 154353358SdimStringRef getMatchingNamespaceTokenText( 155353358Sdim const AnnotatedLine *Line, 156353358Sdim const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 157353358Sdim const FormatToken *NamespaceToken = 158353358Sdim getMatchingNamespaceToken(Line, AnnotatedLines); 159353358Sdim return NamespaceToken ? NamespaceToken->TokenText : StringRef(); 160353358Sdim} 161353358Sdim 162277325Sdimclass LineJoiner { 163277325Sdimpublic: 164288943Sdim LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords, 165288943Sdim const SmallVectorImpl<AnnotatedLine *> &Lines) 166321369Sdim : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()), 167321369Sdim AnnotatedLines(Lines) {} 168277325Sdim 169341825Sdim /// Returns the next line, merging multiple lines into one if possible. 170288943Sdim const AnnotatedLine *getNextMergedLine(bool DryRun, 171288943Sdim LevelIndentTracker &IndentTracker) { 172288943Sdim if (Next == End) 173288943Sdim return nullptr; 174288943Sdim const AnnotatedLine *Current = *Next; 175288943Sdim IndentTracker.nextLine(*Current); 176327952Sdim unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End); 177288943Sdim if (MergedLines > 0 && Style.ColumnLimit == 0) 178288943Sdim // Disallow line merging if there is a break at the start of one of the 179288943Sdim // input lines. 180288943Sdim for (unsigned i = 0; i < MergedLines; ++i) 181288943Sdim if (Next[i + 1]->First->NewlinesBefore > 0) 182288943Sdim MergedLines = 0; 183288943Sdim if (!DryRun) 184288943Sdim for (unsigned i = 0; i < MergedLines; ++i) 185314564Sdim join(*Next[0], *Next[i + 1]); 186288943Sdim Next = Next + MergedLines + 1; 187288943Sdim return Current; 188288943Sdim } 189288943Sdim 190288943Sdimprivate: 191341825Sdim /// Calculates how many lines can be merged into 1 starting at \p I. 192277325Sdim unsigned 193321369Sdim tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker, 194277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator I, 195277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator E) { 196321369Sdim const unsigned Indent = IndentTracker.getIndent(); 197321369Sdim 198288943Sdim // Can't join the last line with anything. 199288943Sdim if (I + 1 == E) 200288943Sdim return 0; 201277325Sdim // We can never merge stuff if there are trailing line comments. 202277325Sdim const AnnotatedLine *TheLine = *I; 203277325Sdim if (TheLine->Last->is(TT_LineComment)) 204277325Sdim return 0; 205288943Sdim if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore) 206288943Sdim return 0; 207288943Sdim if (TheLine->InPPDirective && 208288943Sdim (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)) 209288943Sdim return 0; 210277325Sdim 211277325Sdim if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) 212277325Sdim return 0; 213277325Sdim 214277325Sdim unsigned Limit = 215277325Sdim Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; 216277325Sdim // If we already exceed the column limit, we set 'Limit' to 0. The different 217277325Sdim // tryMerge..() functions can then decide whether to still do merging. 218277325Sdim Limit = TheLine->Last->TotalLength > Limit 219277325Sdim ? 0 220277325Sdim : Limit - TheLine->Last->TotalLength; 221277325Sdim 222321369Sdim if (TheLine->Last->is(TT_FunctionLBrace) && 223321369Sdim TheLine->First == TheLine->Last && 224321369Sdim !Style.BraceWrapping.SplitEmptyFunction && 225321369Sdim I[1]->First->is(tok::r_brace)) 226321369Sdim return tryMergeSimpleBlock(I, E, Limit); 227321369Sdim 228321369Sdim // Handle empty record blocks where the brace has already been wrapped 229321369Sdim if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last && 230321369Sdim I != AnnotatedLines.begin()) { 231321369Sdim bool EmptyBlock = I[1]->First->is(tok::r_brace); 232321369Sdim 233321369Sdim const FormatToken *Tok = I[-1]->First; 234321369Sdim if (Tok && Tok->is(tok::comment)) 235321369Sdim Tok = Tok->getNextNonComment(); 236321369Sdim 237321369Sdim if (Tok && Tok->getNamespaceToken()) 238321369Sdim return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock 239327952Sdim ? tryMergeSimpleBlock(I, E, Limit) 240327952Sdim : 0; 241321369Sdim 242321369Sdim if (Tok && Tok->is(tok::kw_typedef)) 243321369Sdim Tok = Tok->getNextNonComment(); 244321369Sdim if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union, 245327952Sdim tok::kw_extern, Keywords.kw_interface)) 246321369Sdim return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock 247327952Sdim ? tryMergeSimpleBlock(I, E, Limit) 248327952Sdim : 0; 249321369Sdim } 250321369Sdim 251277325Sdim // FIXME: TheLine->Level != 0 might or might not be the right check to do. 252277325Sdim // If necessary, change to something smarter. 253277325Sdim bool MergeShortFunctions = 254277325Sdim Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || 255288943Sdim (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && 256277325Sdim I[1]->First->is(tok::r_brace)) || 257321369Sdim (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly && 258277325Sdim TheLine->Level != 0); 259277325Sdim 260321369Sdim if (Style.CompactNamespaces) { 261353358Sdim if (auto nsToken = TheLine->First->getNamespaceToken()) { 262321369Sdim int i = 0; 263341825Sdim unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1; 264353358Sdim for (; I + 1 + i != E && 265353358Sdim nsToken->TokenText == getNamespaceTokenText(I[i + 1]) && 266341825Sdim closingLine == I[i + 1]->MatchingClosingBlockLineIndex && 267321369Sdim I[i + 1]->Last->TotalLength < Limit; 268321369Sdim i++, closingLine--) { 269321369Sdim // No extra indent for compacted namespaces 270321369Sdim IndentTracker.skipLine(*I[i + 1]); 271321369Sdim 272321369Sdim Limit -= I[i + 1]->Last->TotalLength; 273321369Sdim } 274321369Sdim return i; 275321369Sdim } 276321369Sdim 277353358Sdim if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) { 278321369Sdim int i = 0; 279321369Sdim unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1; 280353358Sdim for (; I + 1 + i != E && 281353358Sdim nsToken->TokenText == 282353358Sdim getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) && 283321369Sdim openingLine == I[i + 1]->MatchingOpeningBlockLineIndex; 284321369Sdim i++, openingLine--) { 285321369Sdim // No space between consecutive braces 286321369Sdim I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace); 287321369Sdim 288321369Sdim // Indent like the outer-most namespace 289321369Sdim IndentTracker.nextLine(*I[i + 1]); 290321369Sdim } 291321369Sdim return i; 292321369Sdim } 293321369Sdim } 294321369Sdim 295327952Sdim // Try to merge a function block with left brace unwrapped 296277325Sdim if (TheLine->Last->is(TT_FunctionLBrace) && 297277325Sdim TheLine->First != TheLine->Last) { 298277325Sdim return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; 299277325Sdim } 300327952Sdim // Try to merge a control statement block with left brace unwrapped 301327952Sdim if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last && 302327952Sdim TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 303360784Sdim return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never 304327952Sdim ? tryMergeSimpleBlock(I, E, Limit) 305327952Sdim : 0; 306327952Sdim } 307327952Sdim // Try to merge a control statement block with left brace wrapped 308327952Sdim if (I[1]->First->is(tok::l_brace) && 309360784Sdim (TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for, 310360784Sdim tok::kw_switch, tok::kw_try, tok::kw_do) || 311360784Sdim (TheLine->First->is(tok::r_brace) && TheLine->First->Next && 312360784Sdim TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) && 313360784Sdim Style.BraceWrapping.AfterControlStatement == 314360784Sdim FormatStyle::BWACS_MultiLine) { 315360784Sdim // If possible, merge the next line's wrapped left brace with the current 316360784Sdim // line. Otherwise, leave it on the next line, as this is a multi-line 317360784Sdim // control statement. 318360784Sdim return (Style.ColumnLimit == 0 || 319360784Sdim TheLine->Last->TotalLength <= Style.ColumnLimit) 320360784Sdim ? 1 321360784Sdim : 0; 322360784Sdim } else if (I[1]->First->is(tok::l_brace) && 323360784Sdim TheLine->First->isOneOf(tok::kw_if, tok::kw_while, 324360784Sdim tok::kw_for)) { 325360784Sdim return (Style.BraceWrapping.AfterControlStatement == 326360784Sdim FormatStyle::BWACS_Always) 327327952Sdim ? tryMergeSimpleBlock(I, E, Limit) 328327952Sdim : 0; 329360784Sdim } else if (I[1]->First->is(tok::l_brace) && 330360784Sdim TheLine->First->isOneOf(tok::kw_else, tok::kw_catch) && 331360784Sdim Style.BraceWrapping.AfterControlStatement == 332360784Sdim FormatStyle::BWACS_MultiLine) { 333360784Sdim // This case if different from the upper BWACS_MultiLine processing 334360784Sdim // in that a preceding r_brace is not on the same line as else/catch 335360784Sdim // most likely because of BeforeElse/BeforeCatch set to true. 336360784Sdim // If the line length doesn't fit ColumnLimit, leave l_brace on the 337360784Sdim // next line to respect the BWACS_MultiLine. 338360784Sdim return (Style.ColumnLimit == 0 || 339360784Sdim TheLine->Last->TotalLength <= Style.ColumnLimit) 340360784Sdim ? 1 341360784Sdim : 0; 342327952Sdim } 343327952Sdim // Try to merge either empty or one-line block if is precedeed by control 344327952Sdim // statement token 345327952Sdim if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last && 346327952Sdim I != AnnotatedLines.begin() && 347327952Sdim I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 348341825Sdim unsigned MergedLines = 0; 349360784Sdim if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never) { 350341825Sdim MergedLines = tryMergeSimpleBlock(I - 1, E, Limit); 351341825Sdim // If we managed to merge the block, discard the first merged line 352341825Sdim // since we are merging starting from I. 353341825Sdim if (MergedLines > 0) 354341825Sdim --MergedLines; 355341825Sdim } 356341825Sdim return MergedLines; 357327952Sdim } 358341825Sdim // Don't merge block with left brace wrapped after ObjC special blocks 359341825Sdim if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() && 360341825Sdim I[-1]->First->is(tok::at) && I[-1]->First->Next) { 361341825Sdim tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID(); 362341825Sdim if (kwId == clang::tok::objc_autoreleasepool || 363341825Sdim kwId == clang::tok::objc_synchronized) 364341825Sdim return 0; 365341825Sdim } 366344779Sdim // Don't merge block with left brace wrapped after case labels 367344779Sdim if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() && 368344779Sdim I[-1]->First->isOneOf(tok::kw_case, tok::kw_default)) 369344779Sdim return 0; 370327952Sdim // Try to merge a block with left brace wrapped that wasn't yet covered 371277325Sdim if (TheLine->Last->is(tok::l_brace)) { 372327952Sdim return !Style.BraceWrapping.AfterFunction || 373327952Sdim (I[1]->First->is(tok::r_brace) && 374327952Sdim !Style.BraceWrapping.SplitEmptyRecord) 375277325Sdim ? tryMergeSimpleBlock(I, E, Limit) 376277325Sdim : 0; 377277325Sdim } 378327952Sdim // Try to merge a function block with left brace wrapped 379277325Sdim if (I[1]->First->is(TT_FunctionLBrace) && 380296417Sdim Style.BraceWrapping.AfterFunction) { 381277325Sdim if (I[1]->Last->is(TT_LineComment)) 382277325Sdim return 0; 383277325Sdim 384277325Sdim // Check for Limit <= 2 to account for the " {". 385277325Sdim if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine))) 386277325Sdim return 0; 387277325Sdim Limit -= 2; 388277325Sdim 389277325Sdim unsigned MergedLines = 0; 390321369Sdim if (MergeShortFunctions || 391321369Sdim (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && 392321369Sdim I[1]->First == I[1]->Last && I + 2 != E && 393321369Sdim I[2]->First->is(tok::r_brace))) { 394277325Sdim MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 395277325Sdim // If we managed to merge the block, count the function header, which is 396277325Sdim // on a separate line. 397277325Sdim if (MergedLines > 0) 398277325Sdim ++MergedLines; 399277325Sdim } 400277325Sdim return MergedLines; 401277325Sdim } 402277325Sdim if (TheLine->First->is(tok::kw_if)) { 403277325Sdim return Style.AllowShortIfStatementsOnASingleLine 404277325Sdim ? tryMergeSimpleControlStatement(I, E, Limit) 405277325Sdim : 0; 406277325Sdim } 407277325Sdim if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { 408277325Sdim return Style.AllowShortLoopsOnASingleLine 409277325Sdim ? tryMergeSimpleControlStatement(I, E, Limit) 410277325Sdim : 0; 411277325Sdim } 412277325Sdim if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) { 413277325Sdim return Style.AllowShortCaseLabelsOnASingleLine 414277325Sdim ? tryMergeShortCaseLabels(I, E, Limit) 415277325Sdim : 0; 416277325Sdim } 417277325Sdim if (TheLine->InPPDirective && 418277325Sdim (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { 419277325Sdim return tryMergeSimplePPDirective(I, E, Limit); 420277325Sdim } 421277325Sdim return 0; 422277325Sdim } 423277325Sdim 424277325Sdim unsigned 425277325Sdim tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 426277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator E, 427277325Sdim unsigned Limit) { 428277325Sdim if (Limit == 0) 429277325Sdim return 0; 430277325Sdim if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) 431277325Sdim return 0; 432277325Sdim if (1 + I[1]->Last->TotalLength > Limit) 433277325Sdim return 0; 434277325Sdim return 1; 435277325Sdim } 436277325Sdim 437277325Sdim unsigned tryMergeSimpleControlStatement( 438277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator I, 439277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { 440277325Sdim if (Limit == 0) 441277325Sdim return 0; 442360784Sdim if (Style.BraceWrapping.AfterControlStatement == 443360784Sdim FormatStyle::BWACS_Always && 444360784Sdim I[1]->First->is(tok::l_brace) && 445360784Sdim Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 446277325Sdim return 0; 447277325Sdim if (I[1]->InPPDirective != (*I)->InPPDirective || 448277325Sdim (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) 449277325Sdim return 0; 450277325Sdim Limit = limitConsideringMacros(I + 1, E, Limit); 451277325Sdim AnnotatedLine &Line = **I; 452277325Sdim if (Line.Last->isNot(tok::r_paren)) 453277325Sdim return 0; 454277325Sdim if (1 + I[1]->Last->TotalLength > Limit) 455277325Sdim return 0; 456288943Sdim if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while, 457288943Sdim TT_LineComment)) 458277325Sdim return 0; 459353358Sdim // Only inline simple if's (no nested if or else), unless specified 460353358Sdim if (Style.AllowShortIfStatementsOnASingleLine != FormatStyle::SIS_Always) { 461353358Sdim if (I + 2 != E && Line.startsWith(tok::kw_if) && 462353358Sdim I[2]->First->is(tok::kw_else)) 463353358Sdim return 0; 464353358Sdim } 465277325Sdim return 1; 466277325Sdim } 467277325Sdim 468288943Sdim unsigned 469288943Sdim tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 470288943Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator E, 471288943Sdim unsigned Limit) { 472277325Sdim if (Limit == 0 || I + 1 == E || 473277325Sdim I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) 474277325Sdim return 0; 475344779Sdim if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace)) 476344779Sdim return 0; 477277325Sdim unsigned NumStmts = 0; 478277325Sdim unsigned Length = 0; 479327952Sdim bool EndsWithComment = false; 480277325Sdim bool InPPDirective = I[0]->InPPDirective; 481327952Sdim const unsigned Level = I[0]->Level; 482277325Sdim for (; NumStmts < 3; ++NumStmts) { 483277325Sdim if (I + 1 + NumStmts == E) 484277325Sdim break; 485277325Sdim const AnnotatedLine *Line = I[1 + NumStmts]; 486277325Sdim if (Line->InPPDirective != InPPDirective) 487277325Sdim break; 488277325Sdim if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 489277325Sdim break; 490277325Sdim if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch, 491327952Sdim tok::kw_while) || 492327952Sdim EndsWithComment) 493277325Sdim return 0; 494327952Sdim if (Line->First->is(tok::comment)) { 495327952Sdim if (Level != Line->Level) 496327952Sdim return 0; 497327952Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts; 498327952Sdim for (; J != E; ++J) { 499327952Sdim Line = *J; 500327952Sdim if (Line->InPPDirective != InPPDirective) 501327952Sdim break; 502327952Sdim if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 503327952Sdim break; 504327952Sdim if (Line->First->isNot(tok::comment) || Level != Line->Level) 505327952Sdim return 0; 506327952Sdim } 507327952Sdim break; 508327952Sdim } 509327952Sdim if (Line->Last->is(tok::comment)) 510327952Sdim EndsWithComment = true; 511277325Sdim Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space. 512277325Sdim } 513277325Sdim if (NumStmts == 0 || NumStmts == 3 || Length > Limit) 514277325Sdim return 0; 515277325Sdim return NumStmts; 516277325Sdim } 517277325Sdim 518277325Sdim unsigned 519277325Sdim tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 520277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator E, 521277325Sdim unsigned Limit) { 522277325Sdim AnnotatedLine &Line = **I; 523277325Sdim 524277325Sdim // Don't merge ObjC @ keywords and methods. 525288943Sdim // FIXME: If an option to allow short exception handling clauses on a single 526288943Sdim // line is added, change this to not return for @try and friends. 527277325Sdim if (Style.Language != FormatStyle::LK_Java && 528277325Sdim Line.First->isOneOf(tok::at, tok::minus, tok::plus)) 529277325Sdim return 0; 530277325Sdim 531277325Sdim // Check that the current line allows merging. This depends on whether we 532277325Sdim // are in a control flow statements as well as several style flags. 533288943Sdim if (Line.First->isOneOf(tok::kw_else, tok::kw_case) || 534288943Sdim (Line.First->Next && Line.First->Next->is(tok::kw_else))) 535277325Sdim return 0; 536344779Sdim // default: in switch statement 537344779Sdim if (Line.First->is(tok::kw_default)) { 538344779Sdim const FormatToken *Tok = Line.First->getNextNonComment(); 539344779Sdim if (Tok && Tok->is(tok::colon)) 540344779Sdim return 0; 541344779Sdim } 542277325Sdim if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try, 543288943Sdim tok::kw___try, tok::kw_catch, tok::kw___finally, 544288943Sdim tok::kw_for, tok::r_brace, Keywords.kw___except)) { 545360784Sdim if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) 546277325Sdim return 0; 547327952Sdim // Don't merge when we can't except the case when 548327952Sdim // the control statement block is empty 549277325Sdim if (!Style.AllowShortIfStatementsOnASingleLine && 550327952Sdim Line.startsWith(tok::kw_if) && 551327952Sdim !Style.BraceWrapping.AfterControlStatement && 552327952Sdim !I[1]->First->is(tok::r_brace)) 553277325Sdim return 0; 554327952Sdim if (!Style.AllowShortIfStatementsOnASingleLine && 555327952Sdim Line.startsWith(tok::kw_if) && 556360784Sdim Style.BraceWrapping.AfterControlStatement == 557360784Sdim FormatStyle::BWACS_Always && 558360784Sdim I + 2 != E && !I[2]->First->is(tok::r_brace)) 559327952Sdim return 0; 560277325Sdim if (!Style.AllowShortLoopsOnASingleLine && 561327952Sdim Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) && 562327952Sdim !Style.BraceWrapping.AfterControlStatement && 563327952Sdim !I[1]->First->is(tok::r_brace)) 564277325Sdim return 0; 565327952Sdim if (!Style.AllowShortLoopsOnASingleLine && 566327952Sdim Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) && 567360784Sdim Style.BraceWrapping.AfterControlStatement == 568360784Sdim FormatStyle::BWACS_Always && 569360784Sdim I + 2 != E && !I[2]->First->is(tok::r_brace)) 570327952Sdim return 0; 571277325Sdim // FIXME: Consider an option to allow short exception handling clauses on 572277325Sdim // a single line. 573288943Sdim // FIXME: This isn't covered by tests. 574288943Sdim // FIXME: For catch, __except, __finally the first token on the line 575288943Sdim // is '}', so this isn't correct here. 576288943Sdim if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch, 577288943Sdim Keywords.kw___except, tok::kw___finally)) 578277325Sdim return 0; 579277325Sdim } 580277325Sdim 581327952Sdim if (Line.Last->is(tok::l_brace)) { 582327952Sdim FormatToken *Tok = I[1]->First; 583327952Sdim if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && 584327952Sdim (Tok->getNextNonComment() == nullptr || 585327952Sdim Tok->getNextNonComment()->is(tok::semi))) { 586327952Sdim // We merge empty blocks even if the line exceeds the column limit. 587360784Sdim Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0; 588327952Sdim Tok->CanBreakBefore = true; 589327952Sdim return 1; 590344779Sdim } else if (Limit != 0 && !Line.startsWithNamespace() && 591327952Sdim !startsExternCBlock(Line)) { 592327952Sdim // We don't merge short records. 593327952Sdim FormatToken *RecordTok = Line.First; 594327952Sdim // Skip record modifiers. 595327952Sdim while (RecordTok->Next && 596327952Sdim RecordTok->isOneOf(tok::kw_typedef, tok::kw_export, 597327952Sdim Keywords.kw_declare, Keywords.kw_abstract, 598327952Sdim tok::kw_default)) 599327952Sdim RecordTok = RecordTok->Next; 600327952Sdim if (RecordTok && 601327952Sdim RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct, 602327952Sdim Keywords.kw_interface)) 603327952Sdim return 0; 604277325Sdim 605327952Sdim // Check that we still have three lines and they fit into the limit. 606327952Sdim if (I + 2 == E || I[2]->Type == LT_Invalid) 607327952Sdim return 0; 608327952Sdim Limit = limitConsideringMacros(I + 2, E, Limit); 609277325Sdim 610327952Sdim if (!nextTwoLinesFitInto(I, Limit)) 611327952Sdim return 0; 612277325Sdim 613327952Sdim // Second, check that the next line does not contain any braces - if it 614327952Sdim // does, readability declines when putting it into a single line. 615327952Sdim if (I[1]->Last->is(TT_LineComment)) 616277325Sdim return 0; 617327952Sdim do { 618327952Sdim if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit) 619327952Sdim return 0; 620327952Sdim Tok = Tok->Next; 621327952Sdim } while (Tok); 622277325Sdim 623327952Sdim // Last, check that the third line starts with a closing brace. 624327952Sdim Tok = I[2]->First; 625327952Sdim if (Tok->isNot(tok::r_brace)) 626327952Sdim return 0; 627327952Sdim 628327952Sdim // Don't merge "if (a) { .. } else {". 629327952Sdim if (Tok->Next && Tok->Next->is(tok::kw_else)) 630327952Sdim return 0; 631327952Sdim 632360784Sdim // Don't merge a trailing multi-line control statement block like: 633360784Sdim // } else if (foo && 634360784Sdim // bar) 635360784Sdim // { <-- current Line 636360784Sdim // baz(); 637360784Sdim // } 638360784Sdim if (Line.First == Line.Last && 639360784Sdim Style.BraceWrapping.AfterControlStatement == 640360784Sdim FormatStyle::BWACS_MultiLine) 641360784Sdim return 0; 642360784Sdim 643327952Sdim return 2; 644327952Sdim } 645327952Sdim } else if (I[1]->First->is(tok::l_brace)) { 646327952Sdim if (I[1]->Last->is(TT_LineComment)) 647277325Sdim return 0; 648277325Sdim 649327952Sdim // Check for Limit <= 2 to account for the " {". 650327952Sdim if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I))) 651288943Sdim return 0; 652327952Sdim Limit -= 2; 653327952Sdim unsigned MergedLines = 0; 654360784Sdim if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never || 655327952Sdim (I[1]->First == I[1]->Last && I + 2 != E && 656327952Sdim I[2]->First->is(tok::r_brace))) { 657327952Sdim MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 658327952Sdim // If we managed to merge the block, count the statement header, which 659327952Sdim // is on a separate line. 660327952Sdim if (MergedLines > 0) 661327952Sdim ++MergedLines; 662327952Sdim } 663327952Sdim return MergedLines; 664277325Sdim } 665277325Sdim return 0; 666277325Sdim } 667277325Sdim 668277325Sdim /// Returns the modified column limit for \p I if it is inside a macro and 669277325Sdim /// needs a trailing '\'. 670277325Sdim unsigned 671277325Sdim limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 672277325Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator E, 673277325Sdim unsigned Limit) { 674277325Sdim if (I[0]->InPPDirective && I + 1 != E && 675277325Sdim !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) { 676277325Sdim return Limit < 2 ? 0 : Limit - 2; 677277325Sdim } 678277325Sdim return Limit; 679277325Sdim } 680277325Sdim 681277325Sdim bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 682277325Sdim unsigned Limit) { 683277325Sdim if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) 684277325Sdim return false; 685277325Sdim return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; 686277325Sdim } 687277325Sdim 688277325Sdim bool containsMustBreak(const AnnotatedLine *Line) { 689277325Sdim for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { 690277325Sdim if (Tok->MustBreakBefore) 691277325Sdim return true; 692277325Sdim } 693277325Sdim return false; 694277325Sdim } 695277325Sdim 696288943Sdim void join(AnnotatedLine &A, const AnnotatedLine &B) { 697288943Sdim assert(!A.Last->Next); 698288943Sdim assert(!B.First->Previous); 699288943Sdim if (B.Affected) 700288943Sdim A.Affected = true; 701288943Sdim A.Last->Next = B.First; 702288943Sdim B.First->Previous = A.Last; 703288943Sdim B.First->CanBreakBefore = true; 704288943Sdim unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; 705288943Sdim for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { 706288943Sdim Tok->TotalLength += LengthA; 707288943Sdim A.Last = Tok; 708288943Sdim } 709288943Sdim } 710288943Sdim 711277325Sdim const FormatStyle &Style; 712288943Sdim const AdditionalKeywords &Keywords; 713288943Sdim const SmallVectorImpl<AnnotatedLine *>::const_iterator End; 714288943Sdim 715288943Sdim SmallVectorImpl<AnnotatedLine *>::const_iterator Next; 716321369Sdim const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines; 717277325Sdim}; 718277325Sdim 719288943Sdimstatic void markFinalized(FormatToken *Tok) { 720288943Sdim for (; Tok; Tok = Tok->Next) { 721288943Sdim Tok->Finalized = true; 722288943Sdim for (AnnotatedLine *Child : Tok->Children) 723288943Sdim markFinalized(Child->First); 724288943Sdim } 725288943Sdim} 726288943Sdim 727288943Sdim#ifndef NDEBUG 728288943Sdimstatic void printLineState(const LineState &State) { 729288943Sdim llvm::dbgs() << "State: "; 730288943Sdim for (const ParenState &P : State.Stack) { 731341825Sdim llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|" 732341825Sdim << P.LastSpace << "|" << P.NestedBlockIndent << " "; 733288943Sdim } 734288943Sdim llvm::dbgs() << State.NextToken->TokenText << "\n"; 735288943Sdim} 736288943Sdim#endif 737288943Sdim 738341825Sdim/// Base class for classes that format one \c AnnotatedLine. 739288943Sdimclass LineFormatter { 740277325Sdimpublic: 741288943Sdim LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, 742288943Sdim const FormatStyle &Style, 743288943Sdim UnwrappedLineFormatter *BlockFormatter) 744288943Sdim : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), 745288943Sdim BlockFormatter(BlockFormatter) {} 746288943Sdim virtual ~LineFormatter() {} 747277325Sdim 748341825Sdim /// Formats an \c AnnotatedLine and returns the penalty. 749288943Sdim /// 750288943Sdim /// If \p DryRun is \c false, directly applies the changes. 751353358Sdim virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 752353358Sdim unsigned FirstStartColumn, bool DryRun) = 0; 753288943Sdim 754288943Sdimprotected: 755341825Sdim /// If the \p State's next token is an r_brace closing a nested block, 756288943Sdim /// format the nested block before it. 757288943Sdim /// 758288943Sdim /// Returns \c true if all children could be placed successfully and adapts 759288943Sdim /// \p Penalty as well as \p State. If \p DryRun is false, also directly 760288943Sdim /// creates changes using \c Whitespaces. 761288943Sdim /// 762288943Sdim /// The crucial idea here is that children always get formatted upon 763288943Sdim /// encountering the closing brace right after the nested block. Now, if we 764288943Sdim /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is 765288943Sdim /// \c false), the entire block has to be kept on the same line (which is only 766288943Sdim /// possible if it fits on the line, only contains a single statement, etc. 767288943Sdim /// 768288943Sdim /// If \p NewLine is true, we format the nested block on separate lines, i.e. 769288943Sdim /// break after the "{", format all lines with correct indentation and the put 770288943Sdim /// the closing "}" on yet another new line. 771288943Sdim /// 772288943Sdim /// This enables us to keep the simple structure of the 773288943Sdim /// \c UnwrappedLineFormatter, where we only have two options for each token: 774288943Sdim /// break or don't break. 775288943Sdim bool formatChildren(LineState &State, bool NewLine, bool DryRun, 776288943Sdim unsigned &Penalty) { 777288943Sdim const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); 778288943Sdim FormatToken &Previous = *State.NextToken->Previous; 779288943Sdim if (!LBrace || LBrace->isNot(tok::l_brace) || 780288943Sdim LBrace->BlockKind != BK_Block || Previous.Children.size() == 0) 781288943Sdim // The previous token does not open a block. Nothing to do. We don't 782288943Sdim // assert so that we can simply call this function for all tokens. 783288943Sdim return true; 784288943Sdim 785288943Sdim if (NewLine) { 786288943Sdim int AdditionalIndent = State.Stack.back().Indent - 787288943Sdim Previous.Children[0]->Level * Style.IndentWidth; 788288943Sdim 789288943Sdim Penalty += 790288943Sdim BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent, 791288943Sdim /*FixBadIndentation=*/true); 792288943Sdim return true; 793288943Sdim } 794288943Sdim 795288943Sdim if (Previous.Children[0]->First->MustBreakBefore) 796288943Sdim return false; 797288943Sdim 798321369Sdim // Cannot merge into one line if this line ends on a comment. 799321369Sdim if (Previous.is(tok::comment)) 800321369Sdim return false; 801321369Sdim 802288943Sdim // Cannot merge multiple statements into a single line. 803288943Sdim if (Previous.Children.size() > 1) 804288943Sdim return false; 805288943Sdim 806321369Sdim const AnnotatedLine *Child = Previous.Children[0]; 807288943Sdim // We can't put the closing "}" on a line with a trailing comment. 808321369Sdim if (Child->Last->isTrailingComment()) 809288943Sdim return false; 810288943Sdim 811288943Sdim // If the child line exceeds the column limit, we wouldn't want to merge it. 812288943Sdim // We add +2 for the trailing " }". 813288943Sdim if (Style.ColumnLimit > 0 && 814321369Sdim Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) 815288943Sdim return false; 816288943Sdim 817288943Sdim if (!DryRun) { 818288943Sdim Whitespaces->replaceWhitespace( 819321369Sdim *Child->First, /*Newlines=*/0, /*Spaces=*/1, 820288943Sdim /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective); 821288943Sdim } 822327952Sdim Penalty += 823327952Sdim formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun); 824288943Sdim 825321369Sdim State.Column += 1 + Child->Last->TotalLength; 826288943Sdim return true; 827288943Sdim } 828288943Sdim 829288943Sdim ContinuationIndenter *Indenter; 830288943Sdim 831288943Sdimprivate: 832288943Sdim WhitespaceManager *Whitespaces; 833288943Sdim const FormatStyle &Style; 834288943Sdim UnwrappedLineFormatter *BlockFormatter; 835288943Sdim}; 836288943Sdim 837341825Sdim/// Formatter that keeps the existing line breaks. 838288943Sdimclass NoColumnLimitLineFormatter : public LineFormatter { 839288943Sdimpublic: 840288943Sdim NoColumnLimitLineFormatter(ContinuationIndenter *Indenter, 841288943Sdim WhitespaceManager *Whitespaces, 842288943Sdim const FormatStyle &Style, 843288943Sdim UnwrappedLineFormatter *BlockFormatter) 844288943Sdim : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 845288943Sdim 846341825Sdim /// Formats the line, simply keeping all of the input's line breaking 847288943Sdim /// decisions. 848288943Sdim unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 849327952Sdim unsigned FirstStartColumn, bool DryRun) override { 850288943Sdim assert(!DryRun); 851327952Sdim LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn, 852327952Sdim &Line, /*DryRun=*/false); 853277325Sdim while (State.NextToken) { 854277325Sdim bool Newline = 855277325Sdim Indenter->mustBreak(State) || 856277325Sdim (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); 857288943Sdim unsigned Penalty = 0; 858288943Sdim formatChildren(State, Newline, /*DryRun=*/false, Penalty); 859277325Sdim Indenter->addTokenToState(State, Newline, /*DryRun=*/false); 860277325Sdim } 861288943Sdim return 0; 862277325Sdim } 863288943Sdim}; 864277325Sdim 865341825Sdim/// Formatter that puts all tokens into a single line without breaks. 866288943Sdimclass NoLineBreakFormatter : public LineFormatter { 867288943Sdimpublic: 868288943Sdim NoLineBreakFormatter(ContinuationIndenter *Indenter, 869288943Sdim WhitespaceManager *Whitespaces, const FormatStyle &Style, 870288943Sdim UnwrappedLineFormatter *BlockFormatter) 871288943Sdim : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 872288943Sdim 873341825Sdim /// Puts all tokens into a single line. 874288943Sdim unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 875327952Sdim unsigned FirstStartColumn, bool DryRun) override { 876288943Sdim unsigned Penalty = 0; 877327952Sdim LineState State = 878327952Sdim Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); 879288943Sdim while (State.NextToken) { 880353358Sdim formatChildren(State, /*NewLine=*/false, DryRun, Penalty); 881321369Sdim Indenter->addTokenToState( 882321369Sdim State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun); 883288943Sdim } 884288943Sdim return Penalty; 885288943Sdim } 886288943Sdim}; 887288943Sdim 888341825Sdim/// Finds the best way to break lines. 889288943Sdimclass OptimizingLineFormatter : public LineFormatter { 890288943Sdimpublic: 891288943Sdim OptimizingLineFormatter(ContinuationIndenter *Indenter, 892288943Sdim WhitespaceManager *Whitespaces, 893288943Sdim const FormatStyle &Style, 894288943Sdim UnwrappedLineFormatter *BlockFormatter) 895288943Sdim : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 896288943Sdim 897341825Sdim /// Formats the line by finding the best line breaks with line lengths 898288943Sdim /// below the column limit. 899288943Sdim unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 900327952Sdim unsigned FirstStartColumn, bool DryRun) override { 901327952Sdim LineState State = 902327952Sdim Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); 903288943Sdim 904288943Sdim // If the ObjC method declaration does not fit on a line, we should format 905288943Sdim // it with one arg per line. 906288943Sdim if (State.Line->Type == LT_ObjCMethodDecl) 907288943Sdim State.Stack.back().BreakBeforeParameter = true; 908288943Sdim 909288943Sdim // Find best solution in solution space. 910288943Sdim return analyzeSolutionSpace(State, DryRun); 911288943Sdim } 912288943Sdim 913277325Sdimprivate: 914288943Sdim struct CompareLineStatePointers { 915288943Sdim bool operator()(LineState *obj1, LineState *obj2) const { 916288943Sdim return *obj1 < *obj2; 917288943Sdim } 918288943Sdim }; 919288943Sdim 920341825Sdim /// A pair of <penalty, count> that is used to prioritize the BFS on. 921288943Sdim /// 922288943Sdim /// In case of equal penalties, we want to prefer states that were inserted 923288943Sdim /// first. During state generation we make sure that we insert states first 924288943Sdim /// that break the line as late as possible. 925288943Sdim typedef std::pair<unsigned, unsigned> OrderedPenalty; 926288943Sdim 927341825Sdim /// An edge in the solution space from \c Previous->State to \c State, 928288943Sdim /// inserting a newline dependent on the \c NewLine. 929288943Sdim struct StateNode { 930288943Sdim StateNode(const LineState &State, bool NewLine, StateNode *Previous) 931288943Sdim : State(State), NewLine(NewLine), Previous(Previous) {} 932288943Sdim LineState State; 933288943Sdim bool NewLine; 934288943Sdim StateNode *Previous; 935288943Sdim }; 936288943Sdim 937341825Sdim /// An item in the prioritized BFS search queue. The \c StateNode's 938288943Sdim /// \c State has the given \c OrderedPenalty. 939288943Sdim typedef std::pair<OrderedPenalty, StateNode *> QueueItem; 940288943Sdim 941341825Sdim /// The BFS queue type. 942288943Sdim typedef std::priority_queue<QueueItem, std::vector<QueueItem>, 943327952Sdim std::greater<QueueItem>> 944327952Sdim QueueType; 945288943Sdim 946341825Sdim /// Analyze the entire solution space starting from \p InitialState. 947288943Sdim /// 948288943Sdim /// This implements a variant of Dijkstra's algorithm on the graph that spans 949288943Sdim /// the solution space (\c LineStates are the nodes). The algorithm tries to 950288943Sdim /// find the shortest path (the one with lowest penalty) from \p InitialState 951288943Sdim /// to a state where all tokens are placed. Returns the penalty. 952288943Sdim /// 953288943Sdim /// If \p DryRun is \c false, directly applies the changes. 954288943Sdim unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) { 955288943Sdim std::set<LineState *, CompareLineStatePointers> Seen; 956288943Sdim 957288943Sdim // Increasing count of \c StateNode items we have created. This is used to 958288943Sdim // create a deterministic order independent of the container. 959288943Sdim unsigned Count = 0; 960288943Sdim QueueType Queue; 961288943Sdim 962288943Sdim // Insert start element into queue. 963288943Sdim StateNode *Node = 964288943Sdim new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); 965288943Sdim Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); 966288943Sdim ++Count; 967288943Sdim 968288943Sdim unsigned Penalty = 0; 969288943Sdim 970288943Sdim // While not empty, take first element and follow edges. 971288943Sdim while (!Queue.empty()) { 972288943Sdim Penalty = Queue.top().first.first; 973288943Sdim StateNode *Node = Queue.top().second; 974288943Sdim if (!Node->State.NextToken) { 975341825Sdim LLVM_DEBUG(llvm::dbgs() 976341825Sdim << "\n---\nPenalty for line: " << Penalty << "\n"); 977288943Sdim break; 978288943Sdim } 979288943Sdim Queue.pop(); 980288943Sdim 981288943Sdim // Cut off the analysis of certain solutions if the analysis gets too 982288943Sdim // complex. See description of IgnoreStackForComparison. 983296417Sdim if (Count > 50000) 984288943Sdim Node->State.IgnoreStackForComparison = true; 985288943Sdim 986288943Sdim if (!Seen.insert(&Node->State).second) 987288943Sdim // State already examined with lower penalty. 988288943Sdim continue; 989288943Sdim 990288943Sdim FormatDecision LastFormat = Node->State.NextToken->Decision; 991288943Sdim if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) 992288943Sdim addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); 993288943Sdim if (LastFormat == FD_Unformatted || LastFormat == FD_Break) 994288943Sdim addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); 995288943Sdim } 996288943Sdim 997288943Sdim if (Queue.empty()) { 998288943Sdim // We were unable to find a solution, do nothing. 999288943Sdim // FIXME: Add diagnostic? 1000341825Sdim LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n"); 1001288943Sdim return 0; 1002288943Sdim } 1003288943Sdim 1004288943Sdim // Reconstruct the solution. 1005288943Sdim if (!DryRun) 1006288943Sdim reconstructPath(InitialState, Queue.top().second); 1007288943Sdim 1008341825Sdim LLVM_DEBUG(llvm::dbgs() 1009341825Sdim << "Total number of analyzed states: " << Count << "\n"); 1010341825Sdim LLVM_DEBUG(llvm::dbgs() << "---\n"); 1011288943Sdim 1012288943Sdim return Penalty; 1013288943Sdim } 1014288943Sdim 1015341825Sdim /// Add the following state to the analysis queue \c Queue. 1016288943Sdim /// 1017288943Sdim /// Assume the current state is \p PreviousNode and has been reached with a 1018288943Sdim /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. 1019288943Sdim void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, 1020288943Sdim bool NewLine, unsigned *Count, QueueType *Queue) { 1021288943Sdim if (NewLine && !Indenter->canBreak(PreviousNode->State)) 1022288943Sdim return; 1023288943Sdim if (!NewLine && Indenter->mustBreak(PreviousNode->State)) 1024288943Sdim return; 1025288943Sdim 1026288943Sdim StateNode *Node = new (Allocator.Allocate()) 1027288943Sdim StateNode(PreviousNode->State, NewLine, PreviousNode); 1028288943Sdim if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) 1029288943Sdim return; 1030288943Sdim 1031288943Sdim Penalty += Indenter->addTokenToState(Node->State, NewLine, true); 1032288943Sdim 1033288943Sdim Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); 1034288943Sdim ++(*Count); 1035288943Sdim } 1036288943Sdim 1037341825Sdim /// Applies the best formatting by reconstructing the path in the 1038288943Sdim /// solution space that leads to \c Best. 1039288943Sdim void reconstructPath(LineState &State, StateNode *Best) { 1040288943Sdim std::deque<StateNode *> Path; 1041288943Sdim // We do not need a break before the initial token. 1042288943Sdim while (Best->Previous) { 1043288943Sdim Path.push_front(Best); 1044288943Sdim Best = Best->Previous; 1045288943Sdim } 1046344779Sdim for (auto I = Path.begin(), E = Path.end(); I != E; ++I) { 1047288943Sdim unsigned Penalty = 0; 1048288943Sdim formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); 1049288943Sdim Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); 1050288943Sdim 1051341825Sdim LLVM_DEBUG({ 1052288943Sdim printLineState((*I)->Previous->State); 1053288943Sdim if ((*I)->NewLine) { 1054288943Sdim llvm::dbgs() << "Penalty for placing " 1055344779Sdim << (*I)->Previous->State.NextToken->Tok.getName() 1056344779Sdim << " on a new line: " << Penalty << "\n"; 1057288943Sdim } 1058288943Sdim }); 1059288943Sdim } 1060288943Sdim } 1061288943Sdim 1062288943Sdim llvm::SpecificBumpPtrAllocator<StateNode> Allocator; 1063277325Sdim}; 1064277325Sdim 1065296417Sdim} // anonymous namespace 1066277325Sdim 1067353358Sdimunsigned UnwrappedLineFormatter::format( 1068353358Sdim const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun, 1069353358Sdim int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn, 1070353358Sdim unsigned NextStartColumn, unsigned LastStartColumn) { 1071288943Sdim LineJoiner Joiner(Style, Keywords, Lines); 1072277325Sdim 1073277325Sdim // Try to look up already computed penalty in DryRun-mode. 1074277325Sdim std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( 1075277325Sdim &Lines, AdditionalIndent); 1076277325Sdim auto CacheIt = PenaltyCache.find(CacheKey); 1077277325Sdim if (DryRun && CacheIt != PenaltyCache.end()) 1078277325Sdim return CacheIt->second; 1079277325Sdim 1080277325Sdim assert(!Lines.empty()); 1081277325Sdim unsigned Penalty = 0; 1082288943Sdim LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level, 1083288943Sdim AdditionalIndent); 1084277325Sdim const AnnotatedLine *PreviousLine = nullptr; 1085288943Sdim const AnnotatedLine *NextLine = nullptr; 1086296417Sdim 1087296417Sdim // The minimum level of consecutive lines that have been formatted. 1088296417Sdim unsigned RangeMinLevel = UINT_MAX; 1089296417Sdim 1090327952Sdim bool FirstLine = true; 1091288943Sdim for (const AnnotatedLine *Line = 1092288943Sdim Joiner.getNextMergedLine(DryRun, IndentTracker); 1093327952Sdim Line; Line = NextLine, FirstLine = false) { 1094288943Sdim const AnnotatedLine &TheLine = *Line; 1095288943Sdim unsigned Indent = IndentTracker.getIndent(); 1096296417Sdim 1097296417Sdim // We continue formatting unchanged lines to adjust their indent, e.g. if a 1098296417Sdim // scope was added. However, we need to carefully stop doing this when we 1099296417Sdim // exit the scope of affected lines to prevent indenting a the entire 1100296417Sdim // remaining file if it currently missing a closing brace. 1101341825Sdim bool PreviousRBrace = 1102341825Sdim PreviousLine && PreviousLine->startsWith(tok::r_brace); 1103296417Sdim bool ContinueFormatting = 1104296417Sdim TheLine.Level > RangeMinLevel || 1105341825Sdim (TheLine.Level == RangeMinLevel && !PreviousRBrace && 1106341825Sdim !TheLine.startsWith(tok::r_brace)); 1107296417Sdim 1108296417Sdim bool FixIndentation = (FixBadIndentation || ContinueFormatting) && 1109296417Sdim Indent != TheLine.First->OriginalColumn; 1110288943Sdim bool ShouldFormat = TheLine.Affected || FixIndentation; 1111288943Sdim // We cannot format this line; if the reason is that the line had a 1112288943Sdim // parsing error, remember that. 1113321369Sdim if (ShouldFormat && TheLine.Type == LT_Invalid && Status) { 1114321369Sdim Status->FormatComplete = false; 1115321369Sdim Status->Line = 1116321369Sdim SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation()); 1117321369Sdim } 1118277325Sdim 1119288943Sdim if (ShouldFormat && TheLine.Type != LT_Invalid) { 1120327952Sdim if (!DryRun) { 1121327952Sdim bool LastLine = Line->First->is(tok::eof); 1122341825Sdim formatFirstToken(TheLine, PreviousLine, Lines, Indent, 1123327952Sdim LastLine ? LastStartColumn : NextStartColumn + Indent); 1124327952Sdim } 1125277325Sdim 1126288943Sdim NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); 1127288943Sdim unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine); 1128288943Sdim bool FitsIntoOneLine = 1129288943Sdim TheLine.Last->TotalLength + Indent <= ColumnLimit || 1130309124Sdim (TheLine.Type == LT_ImportStatement && 1131309124Sdim (Style.Language != FormatStyle::LK_JavaScript || 1132353358Sdim !Style.JavaScriptWrapImports)) || 1133353358Sdim (Style.isCSharp() && 1134353358Sdim TheLine.InPPDirective); // don't split #regions in C# 1135288943Sdim if (Style.ColumnLimit == 0) 1136288943Sdim NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this) 1137327952Sdim .formatLine(TheLine, NextStartColumn + Indent, 1138327952Sdim FirstLine ? FirstStartColumn : 0, DryRun); 1139288943Sdim else if (FitsIntoOneLine) 1140288943Sdim Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this) 1141327952Sdim .formatLine(TheLine, NextStartColumn + Indent, 1142327952Sdim FirstLine ? FirstStartColumn : 0, DryRun); 1143288943Sdim else 1144288943Sdim Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this) 1145327952Sdim .formatLine(TheLine, NextStartColumn + Indent, 1146327952Sdim FirstLine ? FirstStartColumn : 0, DryRun); 1147296417Sdim RangeMinLevel = std::min(RangeMinLevel, TheLine.Level); 1148277325Sdim } else { 1149288943Sdim // If no token in the current line is affected, we still need to format 1150288943Sdim // affected children. 1151288943Sdim if (TheLine.ChildrenAffected) 1152309124Sdim for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) 1153309124Sdim if (!Tok->Children.empty()) 1154309124Sdim format(Tok->Children, DryRun); 1155277325Sdim 1156288943Sdim // Adapt following lines on the current indent level to the same level 1157288943Sdim // unless the current \c AnnotatedLine is not at the beginning of a line. 1158288943Sdim bool StartsNewLine = 1159288943Sdim TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst; 1160288943Sdim if (StartsNewLine) 1161288943Sdim IndentTracker.adjustToUnmodifiedLine(TheLine); 1162288943Sdim if (!DryRun) { 1163288943Sdim bool ReformatLeadingWhitespace = 1164288943Sdim StartsNewLine && ((PreviousLine && PreviousLine->Affected) || 1165288943Sdim TheLine.LeadingEmptyLinesAffected); 1166288943Sdim // Format the first token. 1167288943Sdim if (ReformatLeadingWhitespace) 1168341825Sdim formatFirstToken(TheLine, PreviousLine, Lines, 1169327952Sdim TheLine.First->OriginalColumn, 1170321369Sdim TheLine.First->OriginalColumn); 1171288943Sdim else 1172288943Sdim Whitespaces->addUntouchableToken(*TheLine.First, 1173288943Sdim TheLine.InPPDirective); 1174288943Sdim 1175288943Sdim // Notify the WhitespaceManager about the unchanged whitespace. 1176288943Sdim for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next) 1177277325Sdim Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 1178277325Sdim } 1179288943Sdim NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); 1180296417Sdim RangeMinLevel = UINT_MAX; 1181277325Sdim } 1182288943Sdim if (!DryRun) 1183288943Sdim markFinalized(TheLine.First); 1184288943Sdim PreviousLine = &TheLine; 1185277325Sdim } 1186277325Sdim PenaltyCache[CacheKey] = Penalty; 1187277325Sdim return Penalty; 1188277325Sdim} 1189277325Sdim 1190341825Sdimvoid UnwrappedLineFormatter::formatFirstToken( 1191341825Sdim const AnnotatedLine &Line, const AnnotatedLine *PreviousLine, 1192341825Sdim const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent, 1193341825Sdim unsigned NewlineIndent) { 1194327952Sdim FormatToken &RootToken = *Line.First; 1195288943Sdim if (RootToken.is(tok::eof)) { 1196288943Sdim unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u); 1197327952Sdim unsigned TokenIndent = Newlines ? NewlineIndent : 0; 1198327952Sdim Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent, 1199327952Sdim TokenIndent); 1200288943Sdim return; 1201288943Sdim } 1202277325Sdim unsigned Newlines = 1203277325Sdim std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 1204277325Sdim // Remove empty lines before "}" where applicable. 1205277325Sdim if (RootToken.is(tok::r_brace) && 1206277325Sdim (!RootToken.Next || 1207341825Sdim (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) && 1208341825Sdim // Do not remove empty lines before namespace closing "}". 1209341825Sdim !getNamespaceToken(&Line, Lines)) 1210277325Sdim Newlines = std::min(Newlines, 1u); 1211327952Sdim // Remove empty lines at the start of nested blocks (lambdas/arrow functions) 1212327952Sdim if (PreviousLine == nullptr && Line.Level > 0) 1213327952Sdim Newlines = std::min(Newlines, 1u); 1214277325Sdim if (Newlines == 0 && !RootToken.IsFirst) 1215277325Sdim Newlines = 1; 1216277325Sdim if (RootToken.IsFirst && !RootToken.HasUnescapedNewline) 1217277325Sdim Newlines = 0; 1218277325Sdim 1219277325Sdim // Remove empty lines after "{". 1220277325Sdim if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine && 1221277325Sdim PreviousLine->Last->is(tok::l_brace) && 1222344779Sdim !PreviousLine->startsWithNamespace() && 1223277325Sdim !startsExternCBlock(*PreviousLine)) 1224277325Sdim Newlines = 1; 1225277325Sdim 1226277325Sdim // Insert extra new line before access specifiers. 1227277325Sdim if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && 1228277325Sdim RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) 1229277325Sdim ++Newlines; 1230277325Sdim 1231277325Sdim // Remove empty lines after access specifiers. 1232288943Sdim if (PreviousLine && PreviousLine->First->isAccessSpecifier() && 1233288943Sdim (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) 1234277325Sdim Newlines = std::min(1u, Newlines); 1235277325Sdim 1236327952Sdim if (Newlines) 1237327952Sdim Indent = NewlineIndent; 1238327952Sdim 1239360784Sdim // If in Whitemsmiths mode, indent start and end of blocks 1240360784Sdim if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) { 1241360784Sdim if (RootToken.isOneOf(tok::l_brace, tok::r_brace, tok::kw_case)) 1242360784Sdim Indent += Style.IndentWidth; 1243360784Sdim } 1244360784Sdim 1245353358Sdim // Preprocessor directives get indented before the hash only if specified 1246353358Sdim if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && 1247353358Sdim (Line.Type == LT_PreprocessorDirective || 1248353358Sdim Line.Type == LT_ImportStatement)) 1249327952Sdim Indent = 0; 1250327952Sdim 1251321369Sdim Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent, 1252321369Sdim Line.InPPDirective && 1253321369Sdim !RootToken.HasUnescapedNewline); 1254277325Sdim} 1255277325Sdim 1256288943Sdimunsigned 1257288943SdimUnwrappedLineFormatter::getColumnLimit(bool InPPDirective, 1258288943Sdim const AnnotatedLine *NextLine) const { 1259288943Sdim // In preprocessor directives reserve two chars for trailing " \" if the 1260288943Sdim // next line continues the preprocessor directive. 1261288943Sdim bool ContinuesPPDirective = 1262288943Sdim InPPDirective && 1263288943Sdim // If there is no next line, this is likely a child line and the parent 1264288943Sdim // continues the preprocessor directive. 1265288943Sdim (!NextLine || 1266288943Sdim (NextLine->InPPDirective && 1267288943Sdim // If there is an unescaped newline between this line and the next, the 1268288943Sdim // next line starts a new preprocessor directive. 1269288943Sdim !NextLine->First->HasUnescapedNewline)); 1270288943Sdim return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0); 1271277325Sdim} 1272277325Sdim 1273277325Sdim} // namespace format 1274277325Sdim} // namespace clang 1275