1 //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "UnwrappedLineFormatter.h" 11 #include "WhitespaceManager.h" 12 #include "llvm/Support/Debug.h" 13 #include <queue> 14 15 #define DEBUG_TYPE "format-formatter" 16 17 namespace clang { 18 namespace format { 19 20 namespace { 21 22 bool startsExternCBlock(const AnnotatedLine &Line) { 23 const FormatToken *Next = Line.First->getNextNonComment(); 24 const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; 25 return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() && 26 NextNext && NextNext->is(tok::l_brace); 27 } 28 29 /// \brief Tracks the indent level of \c AnnotatedLines across levels. 30 /// 31 /// \c nextLine must be called for each \c AnnotatedLine, after which \c 32 /// getIndent() will return the indent for the last line \c nextLine was called 33 /// with. 34 /// If the line is not formatted (and thus the indent does not change), calling 35 /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause 36 /// subsequent lines on the same level to be indented at the same level as the 37 /// given line. 38 class LevelIndentTracker { 39 public: 40 LevelIndentTracker(const FormatStyle &Style, 41 const AdditionalKeywords &Keywords, unsigned StartLevel, 42 int AdditionalIndent) 43 : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) { 44 for (unsigned i = 0; i != StartLevel; ++i) 45 IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent); 46 } 47 48 /// \brief Returns the indent for the current line. 49 unsigned getIndent() const { return Indent; } 50 51 /// \brief Update the indent state given that \p Line is going to be formatted 52 /// next. 53 void nextLine(const AnnotatedLine &Line) { 54 Offset = getIndentOffset(*Line.First); 55 // Update the indent level cache size so that we can rely on it 56 // having the right size in adjustToUnmodifiedline. 57 while (IndentForLevel.size() <= Line.Level) 58 IndentForLevel.push_back(-1); 59 if (Line.InPPDirective) { 60 Indent = Line.Level * Style.IndentWidth + AdditionalIndent; 61 } else { 62 IndentForLevel.resize(Line.Level + 1); 63 Indent = getIndent(IndentForLevel, Line.Level); 64 } 65 if (static_cast<int>(Indent) + Offset >= 0) 66 Indent += Offset; 67 } 68 69 /// \brief Update the indent state given that \p Line indent should be 70 /// skipped. 71 void skipLine(const AnnotatedLine &Line) { 72 while (IndentForLevel.size() <= Line.Level) 73 IndentForLevel.push_back(Indent); 74 } 75 76 /// \brief Update the level indent to adapt to the given \p Line. 77 /// 78 /// When a line is not formatted, we move the subsequent lines on the same 79 /// level to the same indent. 80 /// Note that \c nextLine must have been called before this method. 81 void adjustToUnmodifiedLine(const AnnotatedLine &Line) { 82 unsigned LevelIndent = Line.First->OriginalColumn; 83 if (static_cast<int>(LevelIndent) - Offset >= 0) 84 LevelIndent -= Offset; 85 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) && 86 !Line.InPPDirective) 87 IndentForLevel[Line.Level] = LevelIndent; 88 } 89 90 private: 91 /// \brief Get the offset of the line relatively to the level. 92 /// 93 /// For example, 'public:' labels in classes are offset by 1 or 2 94 /// characters to the left from their level. 95 int getIndentOffset(const FormatToken &RootToken) { 96 if (Style.Language == FormatStyle::LK_Java || 97 Style.Language == FormatStyle::LK_JavaScript) 98 return 0; 99 if (RootToken.isAccessSpecifier(false) || 100 RootToken.isObjCAccessSpecifier() || 101 (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) && 102 RootToken.Next && RootToken.Next->is(tok::colon))) 103 return Style.AccessModifierOffset; 104 return 0; 105 } 106 107 /// \brief Get the indent of \p Level from \p IndentForLevel. 108 /// 109 /// \p IndentForLevel must contain the indent for the level \c l 110 /// at \p IndentForLevel[l], or a value < 0 if the indent for 111 /// that level is unknown. 112 unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) { 113 if (IndentForLevel[Level] != -1) 114 return IndentForLevel[Level]; 115 if (Level == 0) 116 return 0; 117 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; 118 } 119 120 const FormatStyle &Style; 121 const AdditionalKeywords &Keywords; 122 const unsigned AdditionalIndent; 123 124 /// \brief The indent in characters for each level. 125 std::vector<int> IndentForLevel; 126 127 /// \brief Offset of the current line relative to the indent level. 128 /// 129 /// For example, the 'public' keywords is often indented with a negative 130 /// offset. 131 int Offset = 0; 132 133 /// \brief The current line's indent. 134 unsigned Indent = 0; 135 }; 136 137 bool isNamespaceDeclaration(const AnnotatedLine *Line) { 138 const FormatToken *NamespaceTok = Line->First; 139 return NamespaceTok && NamespaceTok->getNamespaceToken(); 140 } 141 142 bool isEndOfNamespace(const AnnotatedLine *Line, 143 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) { 144 if (!Line->startsWith(tok::r_brace)) 145 return false; 146 size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; 147 if (StartLineIndex == UnwrappedLine::kInvalidIndex) 148 return false; 149 assert(StartLineIndex < AnnotatedLines.size()); 150 return isNamespaceDeclaration(AnnotatedLines[StartLineIndex]); 151 } 152 153 class LineJoiner { 154 public: 155 LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords, 156 const SmallVectorImpl<AnnotatedLine *> &Lines) 157 : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()), 158 AnnotatedLines(Lines) {} 159 160 /// \brief Returns the next line, merging multiple lines into one if possible. 161 const AnnotatedLine *getNextMergedLine(bool DryRun, 162 LevelIndentTracker &IndentTracker) { 163 if (Next == End) 164 return nullptr; 165 const AnnotatedLine *Current = *Next; 166 IndentTracker.nextLine(*Current); 167 unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End); 168 if (MergedLines > 0 && Style.ColumnLimit == 0) 169 // Disallow line merging if there is a break at the start of one of the 170 // input lines. 171 for (unsigned i = 0; i < MergedLines; ++i) 172 if (Next[i + 1]->First->NewlinesBefore > 0) 173 MergedLines = 0; 174 if (!DryRun) 175 for (unsigned i = 0; i < MergedLines; ++i) 176 join(*Next[0], *Next[i + 1]); 177 Next = Next + MergedLines + 1; 178 return Current; 179 } 180 181 private: 182 /// \brief Calculates how many lines can be merged into 1 starting at \p I. 183 unsigned 184 tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker, 185 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 186 SmallVectorImpl<AnnotatedLine *>::const_iterator E) { 187 const unsigned Indent = IndentTracker.getIndent(); 188 189 // Can't join the last line with anything. 190 if (I + 1 == E) 191 return 0; 192 // We can never merge stuff if there are trailing line comments. 193 const AnnotatedLine *TheLine = *I; 194 if (TheLine->Last->is(TT_LineComment)) 195 return 0; 196 if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore) 197 return 0; 198 if (TheLine->InPPDirective && 199 (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)) 200 return 0; 201 202 if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) 203 return 0; 204 205 unsigned Limit = 206 Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; 207 // If we already exceed the column limit, we set 'Limit' to 0. The different 208 // tryMerge..() functions can then decide whether to still do merging. 209 Limit = TheLine->Last->TotalLength > Limit 210 ? 0 211 : Limit - TheLine->Last->TotalLength; 212 213 if (TheLine->Last->is(TT_FunctionLBrace) && 214 TheLine->First == TheLine->Last && 215 !Style.BraceWrapping.SplitEmptyFunction && 216 I[1]->First->is(tok::r_brace)) 217 return tryMergeSimpleBlock(I, E, Limit); 218 219 // Handle empty record blocks where the brace has already been wrapped 220 if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last && 221 I != AnnotatedLines.begin()) { 222 bool EmptyBlock = I[1]->First->is(tok::r_brace); 223 224 const FormatToken *Tok = I[-1]->First; 225 if (Tok && Tok->is(tok::comment)) 226 Tok = Tok->getNextNonComment(); 227 228 if (Tok && Tok->getNamespaceToken()) 229 return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock 230 ? tryMergeSimpleBlock(I, E, Limit) 231 : 0; 232 233 if (Tok && Tok->is(tok::kw_typedef)) 234 Tok = Tok->getNextNonComment(); 235 if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union, 236 tok::kw_extern, Keywords.kw_interface)) 237 return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock 238 ? tryMergeSimpleBlock(I, E, Limit) 239 : 0; 240 } 241 242 // FIXME: TheLine->Level != 0 might or might not be the right check to do. 243 // If necessary, change to something smarter. 244 bool MergeShortFunctions = 245 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All || 246 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && 247 I[1]->First->is(tok::r_brace)) || 248 (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly && 249 TheLine->Level != 0); 250 251 if (Style.CompactNamespaces) { 252 if (isNamespaceDeclaration(TheLine)) { 253 int i = 0; 254 unsigned closingLine = TheLine->MatchingOpeningBlockLineIndex - 1; 255 for (; I + 1 + i != E && isNamespaceDeclaration(I[i + 1]) && 256 closingLine == I[i + 1]->MatchingOpeningBlockLineIndex && 257 I[i + 1]->Last->TotalLength < Limit; 258 i++, closingLine--) { 259 // No extra indent for compacted namespaces 260 IndentTracker.skipLine(*I[i + 1]); 261 262 Limit -= I[i + 1]->Last->TotalLength; 263 } 264 return i; 265 } 266 267 if (isEndOfNamespace(TheLine, AnnotatedLines)) { 268 int i = 0; 269 unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1; 270 for (; I + 1 + i != E && isEndOfNamespace(I[i + 1], AnnotatedLines) && 271 openingLine == I[i + 1]->MatchingOpeningBlockLineIndex; 272 i++, openingLine--) { 273 // No space between consecutive braces 274 I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace); 275 276 // Indent like the outer-most namespace 277 IndentTracker.nextLine(*I[i + 1]); 278 } 279 return i; 280 } 281 } 282 283 // Try to merge a function block with left brace unwrapped 284 if (TheLine->Last->is(TT_FunctionLBrace) && 285 TheLine->First != TheLine->Last) { 286 return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; 287 } 288 // Try to merge a control statement block with left brace unwrapped 289 if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last && 290 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 291 return Style.AllowShortBlocksOnASingleLine 292 ? tryMergeSimpleBlock(I, E, Limit) 293 : 0; 294 } 295 // Try to merge a control statement block with left brace wrapped 296 if (I[1]->First->is(tok::l_brace) && 297 TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 298 return Style.BraceWrapping.AfterControlStatement 299 ? tryMergeSimpleBlock(I, E, Limit) 300 : 0; 301 } 302 // Try to merge either empty or one-line block if is precedeed by control 303 // statement token 304 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last && 305 I != AnnotatedLines.begin() && 306 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) { 307 return Style.AllowShortBlocksOnASingleLine 308 ? tryMergeSimpleBlock(I - 1, E, Limit) 309 : 0; 310 } 311 // Try to merge a block with left brace wrapped that wasn't yet covered 312 if (TheLine->Last->is(tok::l_brace)) { 313 return !Style.BraceWrapping.AfterFunction || 314 (I[1]->First->is(tok::r_brace) && 315 !Style.BraceWrapping.SplitEmptyRecord) 316 ? tryMergeSimpleBlock(I, E, Limit) 317 : 0; 318 } 319 // Try to merge a function block with left brace wrapped 320 if (I[1]->First->is(TT_FunctionLBrace) && 321 Style.BraceWrapping.AfterFunction) { 322 if (I[1]->Last->is(TT_LineComment)) 323 return 0; 324 325 // Check for Limit <= 2 to account for the " {". 326 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine))) 327 return 0; 328 Limit -= 2; 329 330 unsigned MergedLines = 0; 331 if (MergeShortFunctions || 332 (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && 333 I[1]->First == I[1]->Last && I + 2 != E && 334 I[2]->First->is(tok::r_brace))) { 335 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 336 // If we managed to merge the block, count the function header, which is 337 // on a separate line. 338 if (MergedLines > 0) 339 ++MergedLines; 340 } 341 return MergedLines; 342 } 343 if (TheLine->First->is(tok::kw_if)) { 344 return Style.AllowShortIfStatementsOnASingleLine 345 ? tryMergeSimpleControlStatement(I, E, Limit) 346 : 0; 347 } 348 if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { 349 return Style.AllowShortLoopsOnASingleLine 350 ? tryMergeSimpleControlStatement(I, E, Limit) 351 : 0; 352 } 353 if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) { 354 return Style.AllowShortCaseLabelsOnASingleLine 355 ? tryMergeShortCaseLabels(I, E, Limit) 356 : 0; 357 } 358 if (TheLine->InPPDirective && 359 (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { 360 return tryMergeSimplePPDirective(I, E, Limit); 361 } 362 return 0; 363 } 364 365 unsigned 366 tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 367 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 368 unsigned Limit) { 369 if (Limit == 0) 370 return 0; 371 if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) 372 return 0; 373 if (1 + I[1]->Last->TotalLength > Limit) 374 return 0; 375 return 1; 376 } 377 378 unsigned tryMergeSimpleControlStatement( 379 SmallVectorImpl<AnnotatedLine *>::const_iterator I, 380 SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) { 381 if (Limit == 0) 382 return 0; 383 if (Style.BraceWrapping.AfterControlStatement && 384 (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine)) 385 return 0; 386 if (I[1]->InPPDirective != (*I)->InPPDirective || 387 (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) 388 return 0; 389 Limit = limitConsideringMacros(I + 1, E, Limit); 390 AnnotatedLine &Line = **I; 391 if (Line.Last->isNot(tok::r_paren)) 392 return 0; 393 if (1 + I[1]->Last->TotalLength > Limit) 394 return 0; 395 if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while, 396 TT_LineComment)) 397 return 0; 398 // Only inline simple if's (no nested if or else). 399 if (I + 2 != E && Line.startsWith(tok::kw_if) && 400 I[2]->First->is(tok::kw_else)) 401 return 0; 402 return 1; 403 } 404 405 unsigned 406 tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 407 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 408 unsigned Limit) { 409 if (Limit == 0 || I + 1 == E || 410 I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) 411 return 0; 412 unsigned NumStmts = 0; 413 unsigned Length = 0; 414 bool EndsWithComment = false; 415 bool InPPDirective = I[0]->InPPDirective; 416 const unsigned Level = I[0]->Level; 417 for (; NumStmts < 3; ++NumStmts) { 418 if (I + 1 + NumStmts == E) 419 break; 420 const AnnotatedLine *Line = I[1 + NumStmts]; 421 if (Line->InPPDirective != InPPDirective) 422 break; 423 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 424 break; 425 if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch, 426 tok::kw_while) || 427 EndsWithComment) 428 return 0; 429 if (Line->First->is(tok::comment)) { 430 if (Level != Line->Level) 431 return 0; 432 SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts; 433 for (; J != E; ++J) { 434 Line = *J; 435 if (Line->InPPDirective != InPPDirective) 436 break; 437 if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) 438 break; 439 if (Line->First->isNot(tok::comment) || Level != Line->Level) 440 return 0; 441 } 442 break; 443 } 444 if (Line->Last->is(tok::comment)) 445 EndsWithComment = true; 446 Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space. 447 } 448 if (NumStmts == 0 || NumStmts == 3 || Length > Limit) 449 return 0; 450 return NumStmts; 451 } 452 453 unsigned 454 tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 455 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 456 unsigned Limit) { 457 AnnotatedLine &Line = **I; 458 459 // Don't merge ObjC @ keywords and methods. 460 // FIXME: If an option to allow short exception handling clauses on a single 461 // line is added, change this to not return for @try and friends. 462 if (Style.Language != FormatStyle::LK_Java && 463 Line.First->isOneOf(tok::at, tok::minus, tok::plus)) 464 return 0; 465 466 // Check that the current line allows merging. This depends on whether we 467 // are in a control flow statements as well as several style flags. 468 if (Line.First->isOneOf(tok::kw_else, tok::kw_case) || 469 (Line.First->Next && Line.First->Next->is(tok::kw_else)) || 470 (I != AnnotatedLines.begin() && I[-1]->Last->is(tok::kw_else))) 471 return 0; 472 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try, 473 tok::kw___try, tok::kw_catch, tok::kw___finally, 474 tok::kw_for, tok::r_brace, Keywords.kw___except)) { 475 if (!Style.AllowShortBlocksOnASingleLine) 476 return 0; 477 // Don't merge when we can't except the case when 478 // the control statement block is empty 479 if (!Style.AllowShortIfStatementsOnASingleLine && 480 Line.startsWith(tok::kw_if) && 481 !Style.BraceWrapping.AfterControlStatement && 482 !I[1]->First->is(tok::r_brace)) 483 return 0; 484 if (!Style.AllowShortIfStatementsOnASingleLine && 485 Line.startsWith(tok::kw_if) && 486 Style.BraceWrapping.AfterControlStatement && I + 2 != E && 487 !I[2]->First->is(tok::r_brace)) 488 return 0; 489 if (!Style.AllowShortLoopsOnASingleLine && 490 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) && 491 !Style.BraceWrapping.AfterControlStatement && 492 !I[1]->First->is(tok::r_brace)) 493 return 0; 494 if (!Style.AllowShortLoopsOnASingleLine && 495 Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) && 496 Style.BraceWrapping.AfterControlStatement && I + 2 != E && 497 !I[2]->First->is(tok::r_brace)) 498 return 0; 499 // FIXME: Consider an option to allow short exception handling clauses on 500 // a single line. 501 // FIXME: This isn't covered by tests. 502 // FIXME: For catch, __except, __finally the first token on the line 503 // is '}', so this isn't correct here. 504 if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch, 505 Keywords.kw___except, tok::kw___finally)) 506 return 0; 507 } 508 509 if (Line.Last->is(tok::l_brace)) { 510 FormatToken *Tok = I[1]->First; 511 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && 512 (Tok->getNextNonComment() == nullptr || 513 Tok->getNextNonComment()->is(tok::semi))) { 514 // We merge empty blocks even if the line exceeds the column limit. 515 Tok->SpacesRequiredBefore = 0; 516 Tok->CanBreakBefore = true; 517 return 1; 518 } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) && 519 !startsExternCBlock(Line)) { 520 // We don't merge short records. 521 FormatToken *RecordTok = 522 Line.First->is(tok::kw_typedef) ? Line.First->Next : Line.First; 523 if (RecordTok && 524 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct, 525 Keywords.kw_interface)) 526 return 0; 527 528 // Check that we still have three lines and they fit into the limit. 529 if (I + 2 == E || I[2]->Type == LT_Invalid) 530 return 0; 531 Limit = limitConsideringMacros(I + 2, E, Limit); 532 533 if (!nextTwoLinesFitInto(I, Limit)) 534 return 0; 535 536 // Second, check that the next line does not contain any braces - if it 537 // does, readability declines when putting it into a single line. 538 if (I[1]->Last->is(TT_LineComment)) 539 return 0; 540 do { 541 if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit) 542 return 0; 543 Tok = Tok->Next; 544 } while (Tok); 545 546 // Last, check that the third line starts with a closing brace. 547 Tok = I[2]->First; 548 if (Tok->isNot(tok::r_brace)) 549 return 0; 550 551 // Don't merge "if (a) { .. } else {". 552 if (Tok->Next && Tok->Next->is(tok::kw_else)) 553 return 0; 554 555 return 2; 556 } 557 } else if (I[1]->First->is(tok::l_brace)) { 558 if (I[1]->Last->is(TT_LineComment)) 559 return 0; 560 561 // Check for Limit <= 2 to account for the " {". 562 if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I))) 563 return 0; 564 Limit -= 2; 565 unsigned MergedLines = 0; 566 if (Style.AllowShortBlocksOnASingleLine || 567 (I[1]->First == I[1]->Last && I + 2 != E && 568 I[2]->First->is(tok::r_brace))) { 569 MergedLines = tryMergeSimpleBlock(I + 1, E, Limit); 570 // If we managed to merge the block, count the statement header, which 571 // is on a separate line. 572 if (MergedLines > 0) 573 ++MergedLines; 574 } 575 return MergedLines; 576 } 577 return 0; 578 } 579 580 /// Returns the modified column limit for \p I if it is inside a macro and 581 /// needs a trailing '\'. 582 unsigned 583 limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 584 SmallVectorImpl<AnnotatedLine *>::const_iterator E, 585 unsigned Limit) { 586 if (I[0]->InPPDirective && I + 1 != E && 587 !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) { 588 return Limit < 2 ? 0 : Limit - 2; 589 } 590 return Limit; 591 } 592 593 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I, 594 unsigned Limit) { 595 if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) 596 return false; 597 return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; 598 } 599 600 bool containsMustBreak(const AnnotatedLine *Line) { 601 for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { 602 if (Tok->MustBreakBefore) 603 return true; 604 } 605 return false; 606 } 607 608 void join(AnnotatedLine &A, const AnnotatedLine &B) { 609 assert(!A.Last->Next); 610 assert(!B.First->Previous); 611 if (B.Affected) 612 A.Affected = true; 613 A.Last->Next = B.First; 614 B.First->Previous = A.Last; 615 B.First->CanBreakBefore = true; 616 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; 617 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { 618 Tok->TotalLength += LengthA; 619 A.Last = Tok; 620 } 621 } 622 623 const FormatStyle &Style; 624 const AdditionalKeywords &Keywords; 625 const SmallVectorImpl<AnnotatedLine *>::const_iterator End; 626 627 SmallVectorImpl<AnnotatedLine *>::const_iterator Next; 628 const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines; 629 }; 630 631 static void markFinalized(FormatToken *Tok) { 632 for (; Tok; Tok = Tok->Next) { 633 Tok->Finalized = true; 634 for (AnnotatedLine *Child : Tok->Children) 635 markFinalized(Child->First); 636 } 637 } 638 639 #ifndef NDEBUG 640 static void printLineState(const LineState &State) { 641 llvm::dbgs() << "State: "; 642 for (const ParenState &P : State.Stack) { 643 llvm::dbgs() << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent 644 << " "; 645 } 646 llvm::dbgs() << State.NextToken->TokenText << "\n"; 647 } 648 #endif 649 650 /// \brief Base class for classes that format one \c AnnotatedLine. 651 class LineFormatter { 652 public: 653 LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, 654 const FormatStyle &Style, 655 UnwrappedLineFormatter *BlockFormatter) 656 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), 657 BlockFormatter(BlockFormatter) {} 658 virtual ~LineFormatter() {} 659 660 /// \brief Formats an \c AnnotatedLine and returns the penalty. 661 /// 662 /// If \p DryRun is \c false, directly applies the changes. 663 virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 664 bool DryRun) = 0; 665 666 protected: 667 /// \brief If the \p State's next token is an r_brace closing a nested block, 668 /// format the nested block before it. 669 /// 670 /// Returns \c true if all children could be placed successfully and adapts 671 /// \p Penalty as well as \p State. If \p DryRun is false, also directly 672 /// creates changes using \c Whitespaces. 673 /// 674 /// The crucial idea here is that children always get formatted upon 675 /// encountering the closing brace right after the nested block. Now, if we 676 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is 677 /// \c false), the entire block has to be kept on the same line (which is only 678 /// possible if it fits on the line, only contains a single statement, etc. 679 /// 680 /// If \p NewLine is true, we format the nested block on separate lines, i.e. 681 /// break after the "{", format all lines with correct indentation and the put 682 /// the closing "}" on yet another new line. 683 /// 684 /// This enables us to keep the simple structure of the 685 /// \c UnwrappedLineFormatter, where we only have two options for each token: 686 /// break or don't break. 687 bool formatChildren(LineState &State, bool NewLine, bool DryRun, 688 unsigned &Penalty) { 689 const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); 690 FormatToken &Previous = *State.NextToken->Previous; 691 if (!LBrace || LBrace->isNot(tok::l_brace) || 692 LBrace->BlockKind != BK_Block || Previous.Children.size() == 0) 693 // The previous token does not open a block. Nothing to do. We don't 694 // assert so that we can simply call this function for all tokens. 695 return true; 696 697 if (NewLine) { 698 int AdditionalIndent = State.Stack.back().Indent - 699 Previous.Children[0]->Level * Style.IndentWidth; 700 701 Penalty += 702 BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent, 703 /*FixBadIndentation=*/true); 704 return true; 705 } 706 707 if (Previous.Children[0]->First->MustBreakBefore) 708 return false; 709 710 // Cannot merge into one line if this line ends on a comment. 711 if (Previous.is(tok::comment)) 712 return false; 713 714 // Cannot merge multiple statements into a single line. 715 if (Previous.Children.size() > 1) 716 return false; 717 718 const AnnotatedLine *Child = Previous.Children[0]; 719 // We can't put the closing "}" on a line with a trailing comment. 720 if (Child->Last->isTrailingComment()) 721 return false; 722 723 // If the child line exceeds the column limit, we wouldn't want to merge it. 724 // We add +2 for the trailing " }". 725 if (Style.ColumnLimit > 0 && 726 Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) 727 return false; 728 729 if (!DryRun) { 730 Whitespaces->replaceWhitespace( 731 *Child->First, /*Newlines=*/0, /*Spaces=*/1, 732 /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective); 733 } 734 Penalty += formatLine(*Child, State.Column + 1, DryRun); 735 736 State.Column += 1 + Child->Last->TotalLength; 737 return true; 738 } 739 740 ContinuationIndenter *Indenter; 741 742 private: 743 WhitespaceManager *Whitespaces; 744 const FormatStyle &Style; 745 UnwrappedLineFormatter *BlockFormatter; 746 }; 747 748 /// \brief Formatter that keeps the existing line breaks. 749 class NoColumnLimitLineFormatter : public LineFormatter { 750 public: 751 NoColumnLimitLineFormatter(ContinuationIndenter *Indenter, 752 WhitespaceManager *Whitespaces, 753 const FormatStyle &Style, 754 UnwrappedLineFormatter *BlockFormatter) 755 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 756 757 /// \brief Formats the line, simply keeping all of the input's line breaking 758 /// decisions. 759 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 760 bool DryRun) override { 761 assert(!DryRun); 762 LineState State = 763 Indenter->getInitialState(FirstIndent, &Line, /*DryRun=*/false); 764 while (State.NextToken) { 765 bool Newline = 766 Indenter->mustBreak(State) || 767 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); 768 unsigned Penalty = 0; 769 formatChildren(State, Newline, /*DryRun=*/false, Penalty); 770 Indenter->addTokenToState(State, Newline, /*DryRun=*/false); 771 } 772 return 0; 773 } 774 }; 775 776 /// \brief Formatter that puts all tokens into a single line without breaks. 777 class NoLineBreakFormatter : public LineFormatter { 778 public: 779 NoLineBreakFormatter(ContinuationIndenter *Indenter, 780 WhitespaceManager *Whitespaces, const FormatStyle &Style, 781 UnwrappedLineFormatter *BlockFormatter) 782 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 783 784 /// \brief Puts all tokens into a single line. 785 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 786 bool DryRun) override { 787 unsigned Penalty = 0; 788 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun); 789 while (State.NextToken) { 790 formatChildren(State, /*Newline=*/false, DryRun, Penalty); 791 Indenter->addTokenToState( 792 State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun); 793 } 794 return Penalty; 795 } 796 }; 797 798 /// \brief Finds the best way to break lines. 799 class OptimizingLineFormatter : public LineFormatter { 800 public: 801 OptimizingLineFormatter(ContinuationIndenter *Indenter, 802 WhitespaceManager *Whitespaces, 803 const FormatStyle &Style, 804 UnwrappedLineFormatter *BlockFormatter) 805 : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} 806 807 /// \brief Formats the line by finding the best line breaks with line lengths 808 /// below the column limit. 809 unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, 810 bool DryRun) override { 811 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun); 812 813 // If the ObjC method declaration does not fit on a line, we should format 814 // it with one arg per line. 815 if (State.Line->Type == LT_ObjCMethodDecl) 816 State.Stack.back().BreakBeforeParameter = true; 817 818 // Find best solution in solution space. 819 return analyzeSolutionSpace(State, DryRun); 820 } 821 822 private: 823 struct CompareLineStatePointers { 824 bool operator()(LineState *obj1, LineState *obj2) const { 825 return *obj1 < *obj2; 826 } 827 }; 828 829 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. 830 /// 831 /// In case of equal penalties, we want to prefer states that were inserted 832 /// first. During state generation we make sure that we insert states first 833 /// that break the line as late as possible. 834 typedef std::pair<unsigned, unsigned> OrderedPenalty; 835 836 /// \brief An edge in the solution space from \c Previous->State to \c State, 837 /// inserting a newline dependent on the \c NewLine. 838 struct StateNode { 839 StateNode(const LineState &State, bool NewLine, StateNode *Previous) 840 : State(State), NewLine(NewLine), Previous(Previous) {} 841 LineState State; 842 bool NewLine; 843 StateNode *Previous; 844 }; 845 846 /// \brief An item in the prioritized BFS search queue. The \c StateNode's 847 /// \c State has the given \c OrderedPenalty. 848 typedef std::pair<OrderedPenalty, StateNode *> QueueItem; 849 850 /// \brief The BFS queue type. 851 typedef std::priority_queue<QueueItem, std::vector<QueueItem>, 852 std::greater<QueueItem>> 853 QueueType; 854 855 /// \brief Analyze the entire solution space starting from \p InitialState. 856 /// 857 /// This implements a variant of Dijkstra's algorithm on the graph that spans 858 /// the solution space (\c LineStates are the nodes). The algorithm tries to 859 /// find the shortest path (the one with lowest penalty) from \p InitialState 860 /// to a state where all tokens are placed. Returns the penalty. 861 /// 862 /// If \p DryRun is \c false, directly applies the changes. 863 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) { 864 std::set<LineState *, CompareLineStatePointers> Seen; 865 866 // Increasing count of \c StateNode items we have created. This is used to 867 // create a deterministic order independent of the container. 868 unsigned Count = 0; 869 QueueType Queue; 870 871 // Insert start element into queue. 872 StateNode *Node = 873 new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); 874 Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); 875 ++Count; 876 877 unsigned Penalty = 0; 878 879 // While not empty, take first element and follow edges. 880 while (!Queue.empty()) { 881 Penalty = Queue.top().first.first; 882 StateNode *Node = Queue.top().second; 883 if (!Node->State.NextToken) { 884 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); 885 break; 886 } 887 Queue.pop(); 888 889 // Cut off the analysis of certain solutions if the analysis gets too 890 // complex. See description of IgnoreStackForComparison. 891 if (Count > 50000) 892 Node->State.IgnoreStackForComparison = true; 893 894 if (!Seen.insert(&Node->State).second) 895 // State already examined with lower penalty. 896 continue; 897 898 FormatDecision LastFormat = Node->State.NextToken->Decision; 899 if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) 900 addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue); 901 if (LastFormat == FD_Unformatted || LastFormat == FD_Break) 902 addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue); 903 } 904 905 if (Queue.empty()) { 906 // We were unable to find a solution, do nothing. 907 // FIXME: Add diagnostic? 908 DEBUG(llvm::dbgs() << "Could not find a solution.\n"); 909 return 0; 910 } 911 912 // Reconstruct the solution. 913 if (!DryRun) 914 reconstructPath(InitialState, Queue.top().second); 915 916 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); 917 DEBUG(llvm::dbgs() << "---\n"); 918 919 return Penalty; 920 } 921 922 /// \brief Add the following state to the analysis queue \c Queue. 923 /// 924 /// Assume the current state is \p PreviousNode and has been reached with a 925 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. 926 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, 927 bool NewLine, unsigned *Count, QueueType *Queue) { 928 if (NewLine && !Indenter->canBreak(PreviousNode->State)) 929 return; 930 if (!NewLine && Indenter->mustBreak(PreviousNode->State)) 931 return; 932 933 StateNode *Node = new (Allocator.Allocate()) 934 StateNode(PreviousNode->State, NewLine, PreviousNode); 935 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) 936 return; 937 938 Penalty += Indenter->addTokenToState(Node->State, NewLine, true); 939 940 Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node)); 941 ++(*Count); 942 } 943 944 /// \brief Applies the best formatting by reconstructing the path in the 945 /// solution space that leads to \c Best. 946 void reconstructPath(LineState &State, StateNode *Best) { 947 std::deque<StateNode *> Path; 948 // We do not need a break before the initial token. 949 while (Best->Previous) { 950 Path.push_front(Best); 951 Best = Best->Previous; 952 } 953 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end(); 954 I != E; ++I) { 955 unsigned Penalty = 0; 956 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); 957 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); 958 959 DEBUG({ 960 printLineState((*I)->Previous->State); 961 if ((*I)->NewLine) { 962 llvm::dbgs() << "Penalty for placing " 963 << (*I)->Previous->State.NextToken->Tok.getName() << ": " 964 << Penalty << "\n"; 965 } 966 }); 967 } 968 } 969 970 llvm::SpecificBumpPtrAllocator<StateNode> Allocator; 971 }; 972 973 } // anonymous namespace 974 975 unsigned 976 UnwrappedLineFormatter::format(const SmallVectorImpl<AnnotatedLine *> &Lines, 977 bool DryRun, int AdditionalIndent, 978 bool FixBadIndentation) { 979 LineJoiner Joiner(Style, Keywords, Lines); 980 981 // Try to look up already computed penalty in DryRun-mode. 982 std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( 983 &Lines, AdditionalIndent); 984 auto CacheIt = PenaltyCache.find(CacheKey); 985 if (DryRun && CacheIt != PenaltyCache.end()) 986 return CacheIt->second; 987 988 assert(!Lines.empty()); 989 unsigned Penalty = 0; 990 LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level, 991 AdditionalIndent); 992 const AnnotatedLine *PreviousLine = nullptr; 993 const AnnotatedLine *NextLine = nullptr; 994 995 // The minimum level of consecutive lines that have been formatted. 996 unsigned RangeMinLevel = UINT_MAX; 997 998 for (const AnnotatedLine *Line = 999 Joiner.getNextMergedLine(DryRun, IndentTracker); 1000 Line; Line = NextLine) { 1001 const AnnotatedLine &TheLine = *Line; 1002 unsigned Indent = IndentTracker.getIndent(); 1003 1004 // We continue formatting unchanged lines to adjust their indent, e.g. if a 1005 // scope was added. However, we need to carefully stop doing this when we 1006 // exit the scope of affected lines to prevent indenting a the entire 1007 // remaining file if it currently missing a closing brace. 1008 bool ContinueFormatting = 1009 TheLine.Level > RangeMinLevel || 1010 (TheLine.Level == RangeMinLevel && !TheLine.startsWith(tok::r_brace)); 1011 1012 bool FixIndentation = (FixBadIndentation || ContinueFormatting) && 1013 Indent != TheLine.First->OriginalColumn; 1014 bool ShouldFormat = TheLine.Affected || FixIndentation; 1015 // We cannot format this line; if the reason is that the line had a 1016 // parsing error, remember that. 1017 if (ShouldFormat && TheLine.Type == LT_Invalid && Status) { 1018 Status->FormatComplete = false; 1019 Status->Line = 1020 SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation()); 1021 } 1022 1023 if (ShouldFormat && TheLine.Type != LT_Invalid) { 1024 if (!DryRun) 1025 formatFirstToken(TheLine, PreviousLine, Indent); 1026 1027 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); 1028 unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine); 1029 bool FitsIntoOneLine = 1030 TheLine.Last->TotalLength + Indent <= ColumnLimit || 1031 (TheLine.Type == LT_ImportStatement && 1032 (Style.Language != FormatStyle::LK_JavaScript || 1033 !Style.JavaScriptWrapImports)); 1034 1035 if (Style.ColumnLimit == 0) 1036 NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this) 1037 .formatLine(TheLine, Indent, DryRun); 1038 else if (FitsIntoOneLine) 1039 Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this) 1040 .formatLine(TheLine, Indent, DryRun); 1041 else 1042 Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this) 1043 .formatLine(TheLine, Indent, DryRun); 1044 RangeMinLevel = std::min(RangeMinLevel, TheLine.Level); 1045 } else { 1046 // If no token in the current line is affected, we still need to format 1047 // affected children. 1048 if (TheLine.ChildrenAffected) 1049 for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) 1050 if (!Tok->Children.empty()) 1051 format(Tok->Children, DryRun); 1052 1053 // Adapt following lines on the current indent level to the same level 1054 // unless the current \c AnnotatedLine is not at the beginning of a line. 1055 bool StartsNewLine = 1056 TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst; 1057 if (StartsNewLine) 1058 IndentTracker.adjustToUnmodifiedLine(TheLine); 1059 if (!DryRun) { 1060 bool ReformatLeadingWhitespace = 1061 StartsNewLine && ((PreviousLine && PreviousLine->Affected) || 1062 TheLine.LeadingEmptyLinesAffected); 1063 // Format the first token. 1064 if (ReformatLeadingWhitespace) 1065 formatFirstToken(TheLine, PreviousLine, 1066 TheLine.First->OriginalColumn); 1067 else 1068 Whitespaces->addUntouchableToken(*TheLine.First, 1069 TheLine.InPPDirective); 1070 1071 // Notify the WhitespaceManager about the unchanged whitespace. 1072 for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next) 1073 Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective); 1074 } 1075 NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); 1076 RangeMinLevel = UINT_MAX; 1077 } 1078 if (!DryRun) 1079 markFinalized(TheLine.First); 1080 PreviousLine = &TheLine; 1081 } 1082 PenaltyCache[CacheKey] = Penalty; 1083 return Penalty; 1084 } 1085 1086 void UnwrappedLineFormatter::formatFirstToken(const AnnotatedLine &Line, 1087 const AnnotatedLine *PreviousLine, 1088 unsigned Indent) { 1089 FormatToken &RootToken = *Line.First; 1090 if (RootToken.is(tok::eof)) { 1091 unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u); 1092 Whitespaces->replaceWhitespace(RootToken, Newlines, /*Spaces=*/0, 1093 /*StartOfTokenColumn=*/0); 1094 return; 1095 } 1096 unsigned Newlines = 1097 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 1098 // Remove empty lines before "}" where applicable. 1099 if (RootToken.is(tok::r_brace) && 1100 (!RootToken.Next || 1101 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next))) 1102 Newlines = std::min(Newlines, 1u); 1103 if (Newlines == 0 && !RootToken.IsFirst) 1104 Newlines = 1; 1105 if (RootToken.IsFirst && !RootToken.HasUnescapedNewline) 1106 Newlines = 0; 1107 1108 // Preprocessor directives get indented after the hash, if indented. 1109 if (Line.Type == LT_PreprocessorDirective || Line.Type == LT_ImportStatement) 1110 Indent = 0; 1111 1112 // Remove empty lines after "{". 1113 if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine && 1114 PreviousLine->Last->is(tok::l_brace) && 1115 PreviousLine->First->isNot(tok::kw_namespace) && 1116 !startsExternCBlock(*PreviousLine)) 1117 Newlines = 1; 1118 1119 // Insert extra new line before access specifiers. 1120 if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) && 1121 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) 1122 ++Newlines; 1123 1124 // Remove empty lines after access specifiers. 1125 if (PreviousLine && PreviousLine->First->isAccessSpecifier() && 1126 (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) 1127 Newlines = std::min(1u, Newlines); 1128 1129 Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent, 1130 Line.InPPDirective && 1131 !RootToken.HasUnescapedNewline); 1132 } 1133 1134 unsigned 1135 UnwrappedLineFormatter::getColumnLimit(bool InPPDirective, 1136 const AnnotatedLine *NextLine) const { 1137 // In preprocessor directives reserve two chars for trailing " \" if the 1138 // next line continues the preprocessor directive. 1139 bool ContinuesPPDirective = 1140 InPPDirective && 1141 // If there is no next line, this is likely a child line and the parent 1142 // continues the preprocessor directive. 1143 (!NextLine || 1144 (NextLine->InPPDirective && 1145 // If there is an unescaped newline between this line and the next, the 1146 // next line starts a new preprocessor directive. 1147 !NextLine->First->HasUnescapedNewline)); 1148 return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0); 1149 } 1150 1151 } // namespace format 1152 } // namespace clang 1153