1 //===--- Format.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 /// \file 11 /// \brief This file implements functions declared in Format.h. This will be 12 /// split into separate files as we go. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #define DEBUG_TYPE "format-formatter" 17 18 #include "BreakableToken.h" 19 #include "TokenAnnotator.h" 20 #include "UnwrappedLineParser.h" 21 #include "WhitespaceManager.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/OperatorPrecedence.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Format/Format.h" 26 #include "clang/Frontend/TextDiagnosticPrinter.h" 27 #include "clang/Lex/Lexer.h" 28 #include "llvm/ADT/STLExtras.h" 29 #include "llvm/Support/Allocator.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/YAMLTraits.h" 32 #include <queue> 33 #include <string> 34 35 namespace llvm { 36 namespace yaml { 37 template <> 38 struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> { 39 static void enumeration(IO &io, 40 clang::format::FormatStyle::LanguageStandard &value) { 41 io.enumCase(value, "C++03", clang::format::FormatStyle::LS_Cpp03); 42 io.enumCase(value, "C++11", clang::format::FormatStyle::LS_Cpp11); 43 io.enumCase(value, "Auto", clang::format::FormatStyle::LS_Auto); 44 } 45 }; 46 47 template <> struct MappingTraits<clang::format::FormatStyle> { 48 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) { 49 if (IO.outputting()) { 50 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", "Mozilla" }; 51 ArrayRef<StringRef> Styles(StylesArray); 52 for (size_t i = 0, e = Styles.size(); i < e; ++i) { 53 StringRef StyleName(Styles[i]); 54 if (Style == clang::format::getPredefinedStyle(StyleName)) { 55 IO.mapOptional("# BasedOnStyle", StyleName); 56 break; 57 } 58 } 59 } else { 60 StringRef BasedOnStyle; 61 IO.mapOptional("BasedOnStyle", BasedOnStyle); 62 if (!BasedOnStyle.empty()) 63 Style = clang::format::getPredefinedStyle(BasedOnStyle); 64 } 65 66 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset); 67 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft); 68 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", 69 Style.AllowAllParametersOfDeclarationOnNextLine); 70 IO.mapOptional("AllowShortIfStatementsOnASingleLine", 71 Style.AllowShortIfStatementsOnASingleLine); 72 IO.mapOptional("BinPackParameters", Style.BinPackParameters); 73 IO.mapOptional("ColumnLimit", Style.ColumnLimit); 74 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", 75 Style.ConstructorInitializerAllOnOneLineOrOnePerLine); 76 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding); 77 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels); 78 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep); 79 IO.mapOptional("ObjCSpaceBeforeProtocolList", 80 Style.ObjCSpaceBeforeProtocolList); 81 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter); 82 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine", 83 Style.PenaltyReturnTypeOnItsOwnLine); 84 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType); 85 IO.mapOptional("SpacesBeforeTrailingComments", 86 Style.SpacesBeforeTrailingComments); 87 IO.mapOptional("Standard", Style.Standard); 88 } 89 }; 90 } 91 } 92 93 namespace clang { 94 namespace format { 95 96 FormatStyle getLLVMStyle() { 97 FormatStyle LLVMStyle; 98 LLVMStyle.AccessModifierOffset = -2; 99 LLVMStyle.AlignEscapedNewlinesLeft = false; 100 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; 101 LLVMStyle.AllowShortIfStatementsOnASingleLine = false; 102 LLVMStyle.BinPackParameters = true; 103 LLVMStyle.ColumnLimit = 80; 104 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 105 LLVMStyle.DerivePointerBinding = false; 106 LLVMStyle.IndentCaseLabels = false; 107 LLVMStyle.MaxEmptyLinesToKeep = 1; 108 LLVMStyle.ObjCSpaceBeforeProtocolList = true; 109 LLVMStyle.PenaltyExcessCharacter = 1000000; 110 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75; 111 LLVMStyle.PointerBindsToType = false; 112 LLVMStyle.SpacesBeforeTrailingComments = 1; 113 LLVMStyle.Standard = FormatStyle::LS_Cpp03; 114 return LLVMStyle; 115 } 116 117 FormatStyle getGoogleStyle() { 118 FormatStyle GoogleStyle; 119 GoogleStyle.AccessModifierOffset = -1; 120 GoogleStyle.AlignEscapedNewlinesLeft = true; 121 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true; 122 GoogleStyle.AllowShortIfStatementsOnASingleLine = true; 123 GoogleStyle.BinPackParameters = true; 124 GoogleStyle.ColumnLimit = 80; 125 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 126 GoogleStyle.DerivePointerBinding = true; 127 GoogleStyle.IndentCaseLabels = true; 128 GoogleStyle.MaxEmptyLinesToKeep = 1; 129 GoogleStyle.ObjCSpaceBeforeProtocolList = false; 130 GoogleStyle.PenaltyExcessCharacter = 1000000; 131 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200; 132 GoogleStyle.PointerBindsToType = true; 133 GoogleStyle.SpacesBeforeTrailingComments = 2; 134 GoogleStyle.Standard = FormatStyle::LS_Auto; 135 return GoogleStyle; 136 } 137 138 FormatStyle getChromiumStyle() { 139 FormatStyle ChromiumStyle = getGoogleStyle(); 140 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; 141 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false; 142 ChromiumStyle.BinPackParameters = false; 143 ChromiumStyle.Standard = FormatStyle::LS_Cpp03; 144 ChromiumStyle.DerivePointerBinding = false; 145 return ChromiumStyle; 146 } 147 148 FormatStyle getMozillaStyle() { 149 FormatStyle MozillaStyle = getLLVMStyle(); 150 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false; 151 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 152 MozillaStyle.DerivePointerBinding = true; 153 MozillaStyle.IndentCaseLabels = true; 154 MozillaStyle.ObjCSpaceBeforeProtocolList = false; 155 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; 156 MozillaStyle.PointerBindsToType = true; 157 return MozillaStyle; 158 } 159 160 FormatStyle getPredefinedStyle(StringRef Name) { 161 if (Name.equals_lower("llvm")) 162 return getLLVMStyle(); 163 if (Name.equals_lower("chromium")) 164 return getChromiumStyle(); 165 if (Name.equals_lower("mozilla")) 166 return getMozillaStyle(); 167 if (Name.equals_lower("google")) 168 return getGoogleStyle(); 169 170 llvm::errs() << "Unknown style " << Name << ", using Google style.\n"; 171 return getGoogleStyle(); 172 } 173 174 llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) { 175 llvm::yaml::Input Input(Text); 176 Input >> *Style; 177 return Input.error(); 178 } 179 180 std::string configurationAsText(const FormatStyle &Style) { 181 std::string Text; 182 llvm::raw_string_ostream Stream(Text); 183 llvm::yaml::Output Output(Stream); 184 // We use the same mapping method for input and output, so we need a non-const 185 // reference here. 186 FormatStyle NonConstStyle = Style; 187 Output << NonConstStyle; 188 return Text; 189 } 190 191 // Returns the length of everything up to the first possible line break after 192 // the ), ], } or > matching \c Tok. 193 static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) { 194 if (Tok.MatchingParen == NULL) 195 return 0; 196 AnnotatedToken *End = Tok.MatchingParen; 197 while (!End->Children.empty() && !End->Children[0].CanBreakBefore) { 198 End = &End->Children[0]; 199 } 200 return End->TotalLength - Tok.TotalLength + 1; 201 } 202 203 class UnwrappedLineFormatter { 204 public: 205 UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr, 206 const AnnotatedLine &Line, unsigned FirstIndent, 207 const AnnotatedToken &RootToken, 208 WhitespaceManager &Whitespaces) 209 : Style(Style), SourceMgr(SourceMgr), Line(Line), 210 FirstIndent(FirstIndent), RootToken(RootToken), 211 Whitespaces(Whitespaces), Count(0) {} 212 213 /// \brief Formats an \c UnwrappedLine. 214 /// 215 /// \returns The column after the last token in the last line of the 216 /// \c UnwrappedLine. 217 unsigned format(const AnnotatedLine *NextLine) { 218 // Initialize state dependent on indent. 219 LineState State; 220 State.Column = FirstIndent; 221 State.NextToken = &RootToken; 222 State.Stack.push_back( 223 ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters, 224 /*NoLineBreak=*/ false)); 225 State.LineContainsContinuedForLoopSection = false; 226 State.ParenLevel = 0; 227 State.StartOfStringLiteral = 0; 228 State.StartOfLineLevel = State.ParenLevel; 229 230 // The first token has already been indented and thus consumed. 231 moveStateToNextToken(State, /*DryRun=*/ false); 232 233 // If everything fits on a single line, just put it there. 234 unsigned ColumnLimit = Style.ColumnLimit; 235 if (NextLine && NextLine->InPPDirective && 236 !NextLine->First.FormatTok.HasUnescapedNewline) 237 ColumnLimit = getColumnLimit(); 238 if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) { 239 while (State.NextToken != NULL) { 240 addTokenToState(false, false, State); 241 } 242 return State.Column; 243 } 244 245 // If the ObjC method declaration does not fit on a line, we should format 246 // it with one arg per line. 247 if (Line.Type == LT_ObjCMethodDecl) 248 State.Stack.back().BreakBeforeParameter = true; 249 250 // Find best solution in solution space. 251 return analyzeSolutionSpace(State); 252 } 253 254 private: 255 void DebugTokenState(const AnnotatedToken &AnnotatedTok) { 256 const Token &Tok = AnnotatedTok.FormatTok.Tok; 257 llvm::dbgs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()), 258 Tok.getLength()); 259 llvm::dbgs(); 260 } 261 262 struct ParenState { 263 ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking, 264 bool NoLineBreak) 265 : Indent(Indent), LastSpace(LastSpace), FirstLessLess(0), 266 BreakBeforeClosingBrace(false), QuestionColumn(0), 267 AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false), 268 NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0), 269 NestedNameSpecifierContinuation(0), CallContinuation(0), 270 VariablePos(0) {} 271 272 /// \brief The position to which a specific parenthesis level needs to be 273 /// indented. 274 unsigned Indent; 275 276 /// \brief The position of the last space on each level. 277 /// 278 /// Used e.g. to break like: 279 /// functionCall(Parameter, otherCall( 280 /// OtherParameter)); 281 unsigned LastSpace; 282 283 /// \brief The position the first "<<" operator encountered on each level. 284 /// 285 /// Used to align "<<" operators. 0 if no such operator has been encountered 286 /// on a level. 287 unsigned FirstLessLess; 288 289 /// \brief Whether a newline needs to be inserted before the block's closing 290 /// brace. 291 /// 292 /// We only want to insert a newline before the closing brace if there also 293 /// was a newline after the beginning left brace. 294 bool BreakBeforeClosingBrace; 295 296 /// \brief The column of a \c ? in a conditional expression; 297 unsigned QuestionColumn; 298 299 /// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple 300 /// lines, in this context. 301 bool AvoidBinPacking; 302 303 /// \brief Break after the next comma (or all the commas in this context if 304 /// \c AvoidBinPacking is \c true). 305 bool BreakBeforeParameter; 306 307 /// \brief Line breaking in this context would break a formatting rule. 308 bool NoLineBreak; 309 310 /// \brief The position of the colon in an ObjC method declaration/call. 311 unsigned ColonPos; 312 313 /// \brief The start of the most recent function in a builder-type call. 314 unsigned StartOfFunctionCall; 315 316 /// \brief If a nested name specifier was broken over multiple lines, this 317 /// contains the start column of the second line. Otherwise 0. 318 unsigned NestedNameSpecifierContinuation; 319 320 /// \brief If a call expression was broken over multiple lines, this 321 /// contains the start column of the second line. Otherwise 0. 322 unsigned CallContinuation; 323 324 /// \brief The column of the first variable name in a variable declaration. 325 /// 326 /// Used to align further variables if necessary. 327 unsigned VariablePos; 328 329 bool operator<(const ParenState &Other) const { 330 if (Indent != Other.Indent) 331 return Indent < Other.Indent; 332 if (LastSpace != Other.LastSpace) 333 return LastSpace < Other.LastSpace; 334 if (FirstLessLess != Other.FirstLessLess) 335 return FirstLessLess < Other.FirstLessLess; 336 if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace) 337 return BreakBeforeClosingBrace; 338 if (QuestionColumn != Other.QuestionColumn) 339 return QuestionColumn < Other.QuestionColumn; 340 if (AvoidBinPacking != Other.AvoidBinPacking) 341 return AvoidBinPacking; 342 if (BreakBeforeParameter != Other.BreakBeforeParameter) 343 return BreakBeforeParameter; 344 if (NoLineBreak != Other.NoLineBreak) 345 return NoLineBreak; 346 if (ColonPos != Other.ColonPos) 347 return ColonPos < Other.ColonPos; 348 if (StartOfFunctionCall != Other.StartOfFunctionCall) 349 return StartOfFunctionCall < Other.StartOfFunctionCall; 350 if (CallContinuation != Other.CallContinuation) 351 return CallContinuation < Other.CallContinuation; 352 if (VariablePos != Other.VariablePos) 353 return VariablePos < Other.VariablePos; 354 return false; 355 } 356 }; 357 358 /// \brief The current state when indenting a unwrapped line. 359 /// 360 /// As the indenting tries different combinations this is copied by value. 361 struct LineState { 362 /// \brief The number of used columns in the current line. 363 unsigned Column; 364 365 /// \brief The token that needs to be next formatted. 366 const AnnotatedToken *NextToken; 367 368 /// \brief \c true if this line contains a continued for-loop section. 369 bool LineContainsContinuedForLoopSection; 370 371 /// \brief The level of nesting inside (), [], <> and {}. 372 unsigned ParenLevel; 373 374 /// \brief The \c ParenLevel at the start of this line. 375 unsigned StartOfLineLevel; 376 377 /// \brief The start column of the string literal, if we're in a string 378 /// literal sequence, 0 otherwise. 379 unsigned StartOfStringLiteral; 380 381 /// \brief A stack keeping track of properties applying to parenthesis 382 /// levels. 383 std::vector<ParenState> Stack; 384 385 /// \brief Comparison operator to be able to used \c LineState in \c map. 386 bool operator<(const LineState &Other) const { 387 if (NextToken != Other.NextToken) 388 return NextToken < Other.NextToken; 389 if (Column != Other.Column) 390 return Column < Other.Column; 391 if (LineContainsContinuedForLoopSection != 392 Other.LineContainsContinuedForLoopSection) 393 return LineContainsContinuedForLoopSection; 394 if (ParenLevel != Other.ParenLevel) 395 return ParenLevel < Other.ParenLevel; 396 if (StartOfLineLevel != Other.StartOfLineLevel) 397 return StartOfLineLevel < Other.StartOfLineLevel; 398 if (StartOfStringLiteral != Other.StartOfStringLiteral) 399 return StartOfStringLiteral < Other.StartOfStringLiteral; 400 return Stack < Other.Stack; 401 } 402 }; 403 404 /// \brief Appends the next token to \p State and updates information 405 /// necessary for indentation. 406 /// 407 /// Puts the token on the current line if \p Newline is \c true and adds a 408 /// line break and necessary indentation otherwise. 409 /// 410 /// If \p DryRun is \c false, also creates and stores the required 411 /// \c Replacement. 412 unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) { 413 const AnnotatedToken &Current = *State.NextToken; 414 const AnnotatedToken &Previous = *State.NextToken->Parent; 415 416 if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) { 417 State.Column += State.NextToken->FormatTok.WhiteSpaceLength + 418 State.NextToken->FormatTok.TokenLength; 419 if (State.NextToken->Children.empty()) 420 State.NextToken = NULL; 421 else 422 State.NextToken = &State.NextToken->Children[0]; 423 return 0; 424 } 425 426 // If we are continuing an expression, we want to indent an extra 4 spaces. 427 unsigned ContinuationIndent = 428 std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4; 429 if (Newline) { 430 unsigned WhitespaceStartColumn = State.Column; 431 if (Current.is(tok::r_brace)) { 432 State.Column = Line.Level * 2; 433 } else if (Current.is(tok::string_literal) && 434 State.StartOfStringLiteral != 0) { 435 State.Column = State.StartOfStringLiteral; 436 State.Stack.back().BreakBeforeParameter = true; 437 } else if (Current.is(tok::lessless) && 438 State.Stack.back().FirstLessLess != 0) { 439 State.Column = State.Stack.back().FirstLessLess; 440 } else if (Current.isOneOf(tok::period, tok::arrow)) { 441 if (State.Stack.back().CallContinuation == 0) { 442 State.Column = ContinuationIndent; 443 State.Stack.back().CallContinuation = State.Column; 444 } else { 445 State.Column = State.Stack.back().CallContinuation; 446 } 447 } else if (Current.Type == TT_ConditionalExpr) { 448 State.Column = State.Stack.back().QuestionColumn; 449 } else if (Previous.is(tok::comma) && 450 State.Stack.back().VariablePos != 0) { 451 State.Column = State.Stack.back().VariablePos; 452 } else if (Previous.ClosesTemplateDeclaration || 453 (Current.Type == TT_StartOfName && State.ParenLevel == 0 && 454 Line.StartsDefinition)) { 455 State.Column = State.Stack.back().Indent; 456 } else if (Current.Type == TT_ObjCSelectorName) { 457 if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) { 458 State.Column = 459 State.Stack.back().ColonPos - Current.FormatTok.TokenLength; 460 } else { 461 State.Column = State.Stack.back().Indent; 462 State.Stack.back().ColonPos = 463 State.Column + Current.FormatTok.TokenLength; 464 } 465 } else if (Current.Type == TT_StartOfName || 466 Previous.isOneOf(tok::coloncolon, tok::equal) || 467 Previous.Type == TT_ObjCMethodExpr) { 468 State.Column = ContinuationIndent; 469 } else { 470 State.Column = State.Stack.back().Indent; 471 // Ensure that we fall back to indenting 4 spaces instead of just 472 // flushing continuations left. 473 if (State.Column == FirstIndent) 474 State.Column += 4; 475 } 476 477 if (Current.is(tok::question)) 478 State.Stack.back().BreakBeforeParameter = true; 479 if ((Previous.isOneOf(tok::comma, tok::semi) && 480 !State.Stack.back().AvoidBinPacking) || 481 Previous.Type == TT_BinaryOperator) 482 State.Stack.back().BreakBeforeParameter = false; 483 484 if (!DryRun) { 485 unsigned NewLines = 1; 486 if (Current.Type == TT_LineComment) 487 NewLines = 488 std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore, 489 Style.MaxEmptyLinesToKeep + 1)); 490 if (!Line.InPPDirective) 491 Whitespaces.replaceWhitespace(Current, NewLines, State.Column, 492 WhitespaceStartColumn); 493 else 494 Whitespaces.replacePPWhitespace(Current, NewLines, State.Column, 495 WhitespaceStartColumn); 496 } 497 498 State.Stack.back().LastSpace = State.Column; 499 if (Current.isOneOf(tok::arrow, tok::period)) 500 State.Stack.back().LastSpace += Current.FormatTok.TokenLength; 501 State.StartOfLineLevel = State.ParenLevel; 502 503 // Any break on this level means that the parent level has been broken 504 // and we need to avoid bin packing there. 505 for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) { 506 State.Stack[i].BreakBeforeParameter = true; 507 } 508 const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment(); 509 if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) && 510 TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope()) 511 State.Stack.back().BreakBeforeParameter = true; 512 513 // If we break after {, we should also break before the corresponding }. 514 if (Previous.is(tok::l_brace)) 515 State.Stack.back().BreakBeforeClosingBrace = true; 516 517 if (State.Stack.back().AvoidBinPacking) { 518 // If we are breaking after '(', '{', '<', this is not bin packing 519 // unless AllowAllParametersOfDeclarationOnNextLine is false. 520 if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) || 521 (!Style.AllowAllParametersOfDeclarationOnNextLine && 522 Line.MustBeDeclaration)) 523 State.Stack.back().BreakBeforeParameter = true; 524 } 525 } else { 526 if (Current.is(tok::equal) && 527 (RootToken.is(tok::kw_for) || State.ParenLevel == 0) && 528 State.Stack.back().VariablePos == 0) { 529 State.Stack.back().VariablePos = State.Column; 530 // Move over * and & if they are bound to the variable name. 531 const AnnotatedToken *Tok = &Previous; 532 while (Tok && 533 State.Stack.back().VariablePos >= Tok->FormatTok.TokenLength) { 534 State.Stack.back().VariablePos -= Tok->FormatTok.TokenLength; 535 if (Tok->SpacesRequiredBefore != 0) 536 break; 537 Tok = Tok->Parent; 538 } 539 if (Previous.PartOfMultiVariableDeclStmt) 540 State.Stack.back().LastSpace = State.Stack.back().VariablePos; 541 } 542 543 unsigned Spaces = State.NextToken->SpacesRequiredBefore; 544 545 if (!DryRun) 546 Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column); 547 548 if (Current.Type == TT_ObjCSelectorName && 549 State.Stack.back().ColonPos == 0) { 550 if (State.Stack.back().Indent + Current.LongestObjCSelectorName > 551 State.Column + Spaces + Current.FormatTok.TokenLength) 552 State.Stack.back().ColonPos = 553 State.Stack.back().Indent + Current.LongestObjCSelectorName; 554 else 555 State.Stack.back().ColonPos = 556 State.Column + Spaces + Current.FormatTok.TokenLength; 557 } 558 559 if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr && 560 Current.Type != TT_LineComment) 561 State.Stack.back().Indent = State.Column + Spaces; 562 if (Previous.is(tok::comma) && !Current.isTrailingComment() && 563 State.Stack.back().AvoidBinPacking) 564 State.Stack.back().NoLineBreak = true; 565 566 State.Column += Spaces; 567 if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for)) 568 // Treat the condition inside an if as if it was a second function 569 // parameter, i.e. let nested calls have an indent of 4. 570 State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(". 571 else if (Previous.is(tok::comma)) 572 State.Stack.back().LastSpace = State.Column; 573 else if ((Previous.Type == TT_BinaryOperator || 574 Previous.Type == TT_ConditionalExpr || 575 Previous.Type == TT_CtorInitializerColon) && 576 getPrecedence(Previous) != prec::Assignment) 577 State.Stack.back().LastSpace = State.Column; 578 else if (Previous.Type == TT_InheritanceColon) 579 State.Stack.back().Indent = State.Column; 580 else if (Previous.opensScope() && !Current.FakeLParens.empty()) 581 // If this function has multiple parameters or a binary expression 582 // parameter, indent nested calls from the start of the first parameter. 583 State.Stack.back().LastSpace = State.Column; 584 } 585 586 return moveStateToNextToken(State, DryRun); 587 } 588 589 /// \brief Mark the next token as consumed in \p State and modify its stacks 590 /// accordingly. 591 unsigned moveStateToNextToken(LineState &State, bool DryRun) { 592 const AnnotatedToken &Current = *State.NextToken; 593 assert(State.Stack.size()); 594 595 if (Current.Type == TT_InheritanceColon) 596 State.Stack.back().AvoidBinPacking = true; 597 if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0) 598 State.Stack.back().FirstLessLess = State.Column; 599 if (Current.is(tok::question)) 600 State.Stack.back().QuestionColumn = State.Column; 601 if (Current.isOneOf(tok::period, tok::arrow) && 602 Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0) 603 State.Stack.back().StartOfFunctionCall = 604 Current.LastInChainOfCalls ? 0 : State.Column + 605 Current.FormatTok.TokenLength; 606 if (Current.Type == TT_CtorInitializerColon) { 607 State.Stack.back().Indent = State.Column + 2; 608 if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine) 609 State.Stack.back().AvoidBinPacking = true; 610 State.Stack.back().BreakBeforeParameter = false; 611 } 612 613 // If return returns a binary expression, align after it. 614 if (Current.is(tok::kw_return) && !Current.FakeLParens.empty()) 615 State.Stack.back().LastSpace = State.Column + 7; 616 617 // In ObjC method declaration we align on the ":" of parameters, but we need 618 // to ensure that we indent parameters on subsequent lines by at least 4. 619 if (Current.Type == TT_ObjCMethodSpecifier) 620 State.Stack.back().Indent += 4; 621 622 // Insert scopes created by fake parenthesis. 623 const AnnotatedToken *Previous = Current.getPreviousNoneComment(); 624 // Don't add extra indentation for the first fake parenthesis after 625 // 'return', assignements or opening <({[. The indentation for these cases 626 // is special cased. 627 bool SkipFirstExtraIndent = 628 Current.is(tok::kw_return) || 629 (Previous && (Previous->opensScope() || 630 getPrecedence(*Previous) == prec::Assignment)); 631 for (SmallVector<prec::Level, 4>::const_reverse_iterator 632 I = Current.FakeLParens.rbegin(), 633 E = Current.FakeLParens.rend(); 634 I != E; ++I) { 635 ParenState NewParenState = State.Stack.back(); 636 NewParenState.Indent = 637 std::max(std::max(State.Column, NewParenState.Indent), 638 State.Stack.back().LastSpace); 639 640 // Always indent conditional expressions. Never indent expression where 641 // the 'operator' is ',', ';' or an assignment (i.e. *I <= 642 // prec::Assignment) as those have different indentation rules. Indent 643 // other expression, unless the indentation needs to be skipped. 644 if (*I == prec::Conditional || 645 (!SkipFirstExtraIndent && *I > prec::Assignment)) 646 NewParenState.Indent += 4; 647 if (Previous && !Previous->opensScope()) 648 NewParenState.BreakBeforeParameter = false; 649 State.Stack.push_back(NewParenState); 650 SkipFirstExtraIndent = false; 651 } 652 653 // If we encounter an opening (, [, { or <, we add a level to our stacks to 654 // prepare for the following tokens. 655 if (Current.opensScope()) { 656 unsigned NewIndent; 657 bool AvoidBinPacking; 658 if (Current.is(tok::l_brace)) { 659 NewIndent = 2 + State.Stack.back().LastSpace; 660 AvoidBinPacking = false; 661 } else { 662 NewIndent = 4 + std::max(State.Stack.back().LastSpace, 663 State.Stack.back().StartOfFunctionCall); 664 AvoidBinPacking = !Style.BinPackParameters; 665 } 666 State.Stack.push_back( 667 ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking, 668 State.Stack.back().NoLineBreak)); 669 670 if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) { 671 // This parenthesis was the last token possibly making use of Indent and 672 // LastSpace of the next higher ParenLevel. Thus, erase them to acieve 673 // better memoization results. 674 State.Stack[State.Stack.size() - 2].Indent = 0; 675 State.Stack[State.Stack.size() - 2].LastSpace = 0; 676 } 677 678 ++State.ParenLevel; 679 } 680 681 // If this '[' opens an ObjC call, determine whether all parameters fit into 682 // one line and put one per line if they don't. 683 if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr && 684 Current.MatchingParen != NULL) { 685 if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit()) 686 State.Stack.back().BreakBeforeParameter = true; 687 } 688 689 // If we encounter a closing ), ], } or >, we can remove a level from our 690 // stacks. 691 if (Current.isOneOf(tok::r_paren, tok::r_square) || 692 (Current.is(tok::r_brace) && State.NextToken != &RootToken) || 693 State.NextToken->Type == TT_TemplateCloser) { 694 State.Stack.pop_back(); 695 --State.ParenLevel; 696 } 697 698 // Remove scopes created by fake parenthesis. 699 for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) { 700 unsigned VariablePos = State.Stack.back().VariablePos; 701 State.Stack.pop_back(); 702 State.Stack.back().VariablePos = VariablePos; 703 } 704 705 if (Current.is(tok::string_literal)) { 706 State.StartOfStringLiteral = State.Column; 707 } else if (Current.isNot(tok::comment)) { 708 State.StartOfStringLiteral = 0; 709 } 710 711 State.Column += Current.FormatTok.TokenLength; 712 713 if (State.NextToken->Children.empty()) 714 State.NextToken = NULL; 715 else 716 State.NextToken = &State.NextToken->Children[0]; 717 718 return breakProtrudingToken(Current, State, DryRun); 719 } 720 721 /// \brief If the current token sticks out over the end of the line, break 722 /// it if possible. 723 unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State, 724 bool DryRun) { 725 llvm::OwningPtr<BreakableToken> Token; 726 unsigned StartColumn = State.Column - Current.FormatTok.TokenLength; 727 if (Current.is(tok::string_literal)) { 728 // Only break up default narrow strings. 729 const char *LiteralData = SourceMgr.getCharacterData( 730 Current.FormatTok.getStartOfNonWhitespace()); 731 if (!LiteralData || *LiteralData != '"') 732 return 0; 733 734 Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok, 735 StartColumn)); 736 } else if (Current.Type == TT_BlockComment) { 737 BreakableBlockComment *BBC = 738 new BreakableBlockComment(SourceMgr, Current, StartColumn); 739 if (!DryRun) 740 BBC->alignLines(Whitespaces); 741 Token.reset(BBC); 742 } else if (Current.Type == TT_LineComment && 743 (Current.Parent == NULL || 744 Current.Parent->Type != TT_ImplicitStringLiteral)) { 745 Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn)); 746 } else { 747 return 0; 748 } 749 750 bool BreakInserted = false; 751 unsigned Penalty = 0; 752 for (unsigned LineIndex = 0; LineIndex < Token->getLineCount(); 753 ++LineIndex) { 754 unsigned TailOffset = 0; 755 unsigned RemainingLength = 756 Token->getLineLengthAfterSplit(LineIndex, TailOffset); 757 while (RemainingLength > getColumnLimit()) { 758 BreakableToken::Split Split = 759 Token->getSplit(LineIndex, TailOffset, getColumnLimit()); 760 if (Split.first == StringRef::npos) 761 break; 762 assert(Split.first != 0); 763 unsigned NewRemainingLength = Token->getLineLengthAfterSplit( 764 LineIndex, TailOffset + Split.first + Split.second); 765 if (NewRemainingLength >= RemainingLength) 766 break; 767 if (!DryRun) { 768 Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective, 769 Whitespaces); 770 } 771 TailOffset += Split.first + Split.second; 772 RemainingLength = NewRemainingLength; 773 Penalty += Style.PenaltyExcessCharacter; 774 BreakInserted = true; 775 } 776 State.Column = RemainingLength; 777 if (!DryRun) { 778 Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces); 779 } 780 } 781 782 if (BreakInserted) { 783 for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) 784 State.Stack[i].BreakBeforeParameter = true; 785 State.Stack.back().LastSpace = StartColumn; 786 } 787 return Penalty; 788 } 789 790 unsigned getColumnLimit() { 791 // In preprocessor directives reserve two chars for trailing " \" 792 return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0); 793 } 794 795 /// \brief An edge in the solution space from \c Previous->State to \c State, 796 /// inserting a newline dependent on the \c NewLine. 797 struct StateNode { 798 StateNode(const LineState &State, bool NewLine, StateNode *Previous) 799 : State(State), NewLine(NewLine), Previous(Previous) {} 800 LineState State; 801 bool NewLine; 802 StateNode *Previous; 803 }; 804 805 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. 806 /// 807 /// In case of equal penalties, we want to prefer states that were inserted 808 /// first. During state generation we make sure that we insert states first 809 /// that break the line as late as possible. 810 typedef std::pair<unsigned, unsigned> OrderedPenalty; 811 812 /// \brief An item in the prioritized BFS search queue. The \c StateNode's 813 /// \c State has the given \c OrderedPenalty. 814 typedef std::pair<OrderedPenalty, StateNode *> QueueItem; 815 816 /// \brief The BFS queue type. 817 typedef std::priority_queue<QueueItem, std::vector<QueueItem>, 818 std::greater<QueueItem> > QueueType; 819 820 /// \brief Analyze the entire solution space starting from \p InitialState. 821 /// 822 /// This implements a variant of Dijkstra's algorithm on the graph that spans 823 /// the solution space (\c LineStates are the nodes). The algorithm tries to 824 /// find the shortest path (the one with lowest penalty) from \p InitialState 825 /// to a state where all tokens are placed. 826 unsigned analyzeSolutionSpace(LineState &InitialState) { 827 std::set<LineState> Seen; 828 829 // Insert start element into queue. 830 StateNode *Node = 831 new (Allocator.Allocate()) StateNode(InitialState, false, NULL); 832 Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); 833 ++Count; 834 835 // While not empty, take first element and follow edges. 836 while (!Queue.empty()) { 837 unsigned Penalty = Queue.top().first.first; 838 StateNode *Node = Queue.top().second; 839 if (Node->State.NextToken == NULL) { 840 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); 841 break; 842 } 843 Queue.pop(); 844 845 if (!Seen.insert(Node->State).second) 846 // State already examined with lower penalty. 847 continue; 848 849 addNextStateToQueue(Penalty, Node, /*NewLine=*/ false); 850 addNextStateToQueue(Penalty, Node, /*NewLine=*/ true); 851 } 852 853 if (Queue.empty()) 854 // We were unable to find a solution, do nothing. 855 // FIXME: Add diagnostic? 856 return 0; 857 858 // Reconstruct the solution. 859 reconstructPath(InitialState, Queue.top().second); 860 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); 861 DEBUG(llvm::dbgs() << "---\n"); 862 863 // Return the column after the last token of the solution. 864 return Queue.top().second->State.Column; 865 } 866 867 void reconstructPath(LineState &State, StateNode *Current) { 868 // FIXME: This recursive implementation limits the possible number 869 // of tokens per line if compiled into a binary with small stack space. 870 // To become more independent of stack frame limitations we would need 871 // to also change the TokenAnnotator. 872 if (Current->Previous == NULL) 873 return; 874 reconstructPath(State, Current->Previous); 875 DEBUG({ 876 if (Current->NewLine) { 877 llvm::dbgs() 878 << "Penalty for splitting before " 879 << Current->Previous->State.NextToken->FormatTok.Tok.getName() 880 << ": " << Current->Previous->State.NextToken->SplitPenalty << "\n"; 881 } 882 }); 883 addTokenToState(Current->NewLine, false, State); 884 } 885 886 /// \brief Add the following state to the analysis queue \c Queue. 887 /// 888 /// Assume the current state is \p PreviousNode and has been reached with a 889 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. 890 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, 891 bool NewLine) { 892 if (NewLine && !canBreak(PreviousNode->State)) 893 return; 894 if (!NewLine && mustBreak(PreviousNode->State)) 895 return; 896 if (NewLine) 897 Penalty += PreviousNode->State.NextToken->SplitPenalty; 898 899 StateNode *Node = new (Allocator.Allocate()) 900 StateNode(PreviousNode->State, NewLine, PreviousNode); 901 Penalty += addTokenToState(NewLine, true, Node->State); 902 if (Node->State.Column > getColumnLimit()) { 903 unsigned ExcessCharacters = Node->State.Column - getColumnLimit(); 904 Penalty += Style.PenaltyExcessCharacter * ExcessCharacters; 905 } 906 907 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node)); 908 ++Count; 909 } 910 911 /// \brief Returns \c true, if a line break after \p State is allowed. 912 bool canBreak(const LineState &State) { 913 if (!State.NextToken->CanBreakBefore && 914 !(State.NextToken->is(tok::r_brace) && 915 State.Stack.back().BreakBeforeClosingBrace)) 916 return false; 917 return !State.Stack.back().NoLineBreak; 918 } 919 920 /// \brief Returns \c true, if a line break after \p State is mandatory. 921 bool mustBreak(const LineState &State) { 922 const AnnotatedToken &Current = *State.NextToken; 923 const AnnotatedToken &Previous = *Current.Parent; 924 if (Current.MustBreakBefore || Current.Type == TT_InlineASMColon) 925 return true; 926 if (Current.is(tok::r_brace) && State.Stack.back().BreakBeforeClosingBrace) 927 return true; 928 if (Previous.is(tok::semi) && State.LineContainsContinuedForLoopSection) 929 return true; 930 if ((Previous.isOneOf(tok::comma, tok::semi) || Current.is(tok::question) || 931 Current.Type == TT_ConditionalExpr) && 932 State.Stack.back().BreakBeforeParameter && 933 !Current.isTrailingComment() && 934 !Current.isOneOf(tok::r_paren, tok::r_brace)) 935 return true; 936 937 // If we need to break somewhere inside the LHS of a binary expression, we 938 // should also break after the operator. 939 if (Previous.Type == TT_BinaryOperator && 940 !Previous.isOneOf(tok::lessless, tok::question) && 941 getPrecedence(Previous) != prec::Assignment && 942 State.Stack.back().BreakBeforeParameter) 943 return true; 944 945 // FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding 946 // out whether it is the first parameter. Clean this up. 947 if (Current.Type == TT_ObjCSelectorName && 948 Current.LongestObjCSelectorName == 0 && 949 State.Stack.back().BreakBeforeParameter) 950 return true; 951 if ((Current.Type == TT_CtorInitializerColon || 952 (Previous.ClosesTemplateDeclaration && State.ParenLevel == 0))) 953 return true; 954 955 // This prevents breaks like: 956 // ... 957 // SomeParameter, OtherParameter).DoSomething( 958 // ... 959 // As they hide "DoSomething" and generally bad for readability. 960 if (Current.isOneOf(tok::period, tok::arrow) && 961 getRemainingLength(State) + State.Column > getColumnLimit() && 962 State.ParenLevel < State.StartOfLineLevel) 963 return true; 964 return false; 965 } 966 967 // Returns the total number of columns required for the remaining tokens. 968 unsigned getRemainingLength(const LineState &State) { 969 if (State.NextToken && State.NextToken->Parent) 970 return Line.Last->TotalLength - State.NextToken->Parent->TotalLength; 971 return 0; 972 } 973 974 FormatStyle Style; 975 SourceManager &SourceMgr; 976 const AnnotatedLine &Line; 977 const unsigned FirstIndent; 978 const AnnotatedToken &RootToken; 979 WhitespaceManager &Whitespaces; 980 981 llvm::SpecificBumpPtrAllocator<StateNode> Allocator; 982 QueueType Queue; 983 // Increasing count of \c StateNode items we have created. This is used 984 // to create a deterministic order independent of the container. 985 unsigned Count; 986 }; 987 988 class LexerBasedFormatTokenSource : public FormatTokenSource { 989 public: 990 LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr) 991 : GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr), 992 IdentTable(Lex.getLangOpts()) { 993 Lex.SetKeepWhitespaceMode(true); 994 } 995 996 virtual FormatToken getNextToken() { 997 if (GreaterStashed) { 998 FormatTok.NewlinesBefore = 0; 999 FormatTok.WhiteSpaceStart = 1000 FormatTok.Tok.getLocation().getLocWithOffset(1); 1001 FormatTok.WhiteSpaceLength = 0; 1002 GreaterStashed = false; 1003 return FormatTok; 1004 } 1005 1006 FormatTok = FormatToken(); 1007 Lex.LexFromRawLexer(FormatTok.Tok); 1008 StringRef Text = rawTokenText(FormatTok.Tok); 1009 FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation(); 1010 if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0) 1011 FormatTok.IsFirst = true; 1012 1013 // Consume and record whitespace until we find a significant token. 1014 while (FormatTok.Tok.is(tok::unknown)) { 1015 unsigned Newlines = Text.count('\n'); 1016 if (Newlines > 0) 1017 FormatTok.LastNewlineOffset = 1018 FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1; 1019 unsigned EscapedNewlines = Text.count("\\\n"); 1020 FormatTok.NewlinesBefore += Newlines; 1021 FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines; 1022 FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength(); 1023 1024 if (FormatTok.Tok.is(tok::eof)) 1025 return FormatTok; 1026 Lex.LexFromRawLexer(FormatTok.Tok); 1027 Text = rawTokenText(FormatTok.Tok); 1028 } 1029 1030 // Now FormatTok is the next non-whitespace token. 1031 FormatTok.TokenLength = Text.size(); 1032 1033 if (FormatTok.Tok.is(tok::comment)) { 1034 FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size(); 1035 FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength; 1036 } 1037 1038 // In case the token starts with escaped newlines, we want to 1039 // take them into account as whitespace - this pattern is quite frequent 1040 // in macro definitions. 1041 // FIXME: What do we want to do with other escaped spaces, and escaped 1042 // spaces or newlines in the middle of tokens? 1043 // FIXME: Add a more explicit test. 1044 unsigned i = 0; 1045 while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') { 1046 // FIXME: ++FormatTok.NewlinesBefore is missing... 1047 FormatTok.WhiteSpaceLength += 2; 1048 FormatTok.TokenLength -= 2; 1049 i += 2; 1050 } 1051 1052 if (FormatTok.Tok.is(tok::raw_identifier)) { 1053 IdentifierInfo &Info = IdentTable.get(Text); 1054 FormatTok.Tok.setIdentifierInfo(&Info); 1055 FormatTok.Tok.setKind(Info.getTokenID()); 1056 } 1057 1058 if (FormatTok.Tok.is(tok::greatergreater)) { 1059 FormatTok.Tok.setKind(tok::greater); 1060 FormatTok.TokenLength = 1; 1061 GreaterStashed = true; 1062 } 1063 1064 return FormatTok; 1065 } 1066 1067 IdentifierTable &getIdentTable() { return IdentTable; } 1068 1069 private: 1070 FormatToken FormatTok; 1071 bool GreaterStashed; 1072 Lexer &Lex; 1073 SourceManager &SourceMgr; 1074 IdentifierTable IdentTable; 1075 1076 /// Returns the text of \c FormatTok. 1077 StringRef rawTokenText(Token &Tok) { 1078 return StringRef(SourceMgr.getCharacterData(Tok.getLocation()), 1079 Tok.getLength()); 1080 } 1081 }; 1082 1083 class Formatter : public UnwrappedLineConsumer { 1084 public: 1085 Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex, 1086 SourceManager &SourceMgr, 1087 const std::vector<CharSourceRange> &Ranges) 1088 : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr), 1089 Whitespaces(SourceMgr, Style), Ranges(Ranges) {} 1090 1091 virtual ~Formatter() {} 1092 1093 tooling::Replacements format() { 1094 LexerBasedFormatTokenSource Tokens(Lex, SourceMgr); 1095 UnwrappedLineParser Parser(Diag, Style, Tokens, *this); 1096 bool StructuralError = Parser.parse(); 1097 unsigned PreviousEndOfLineColumn = 0; 1098 TokenAnnotator Annotator(Style, SourceMgr, Lex, 1099 Tokens.getIdentTable().get("in")); 1100 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1101 Annotator.annotate(AnnotatedLines[i]); 1102 } 1103 deriveLocalStyle(); 1104 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1105 Annotator.calculateFormattingInformation(AnnotatedLines[i]); 1106 } 1107 1108 // Adapt level to the next line if this is a comment. 1109 // FIXME: Can/should this be done in the UnwrappedLineParser? 1110 const AnnotatedLine *NextNoneCommentLine = NULL; 1111 for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) { 1112 if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) && 1113 AnnotatedLines[i].First.Children.empty()) 1114 AnnotatedLines[i].Level = NextNoneCommentLine->Level; 1115 else 1116 NextNoneCommentLine = 1117 AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i] 1118 : NULL; 1119 } 1120 1121 std::vector<int> IndentForLevel; 1122 bool PreviousLineWasTouched = false; 1123 const AnnotatedToken *PreviousLineLastToken = 0; 1124 bool FormatPPDirective = false; 1125 for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(), 1126 E = AnnotatedLines.end(); 1127 I != E; ++I) { 1128 const AnnotatedLine &TheLine = *I; 1129 const FormatToken &FirstTok = TheLine.First.FormatTok; 1130 int Offset = getIndentOffset(TheLine.First); 1131 1132 // Check whether this line is part of a formatted preprocessor directive. 1133 if (FirstTok.HasUnescapedNewline) 1134 FormatPPDirective = false; 1135 if (!FormatPPDirective && TheLine.InPPDirective && 1136 (touchesLine(TheLine) || touchesPPDirective(I + 1, E))) 1137 FormatPPDirective = true; 1138 1139 while (IndentForLevel.size() <= TheLine.Level) 1140 IndentForLevel.push_back(-1); 1141 IndentForLevel.resize(TheLine.Level + 1); 1142 bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0; 1143 if (TheLine.First.is(tok::eof)) { 1144 if (PreviousLineWasTouched) { 1145 unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u); 1146 Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0, 1147 /*WhitespaceStartColumn*/ 0); 1148 } 1149 } else if (TheLine.Type != LT_Invalid && 1150 (WasMoved || FormatPPDirective || touchesLine(TheLine))) { 1151 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level); 1152 unsigned Indent = LevelIndent; 1153 if (static_cast<int>(Indent) + Offset >= 0) 1154 Indent += Offset; 1155 if (FirstTok.WhiteSpaceStart.isValid() && 1156 // Insert a break even if there is a structural error in case where 1157 // we break apart a line consisting of multiple unwrapped lines. 1158 (FirstTok.NewlinesBefore == 0 || !StructuralError)) { 1159 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent, 1160 TheLine.InPPDirective, PreviousEndOfLineColumn); 1161 } else { 1162 Indent = LevelIndent = 1163 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1; 1164 } 1165 tryFitMultipleLinesInOne(Indent, I, E); 1166 UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent, 1167 TheLine.First, Whitespaces); 1168 PreviousEndOfLineColumn = 1169 Formatter.format(I + 1 != E ? &*(I + 1) : NULL); 1170 IndentForLevel[TheLine.Level] = LevelIndent; 1171 PreviousLineWasTouched = true; 1172 } else { 1173 if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) { 1174 unsigned Indent = 1175 SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1; 1176 unsigned LevelIndent = Indent; 1177 if (static_cast<int>(LevelIndent) - Offset >= 0) 1178 LevelIndent -= Offset; 1179 if (TheLine.First.isNot(tok::comment)) 1180 IndentForLevel[TheLine.Level] = LevelIndent; 1181 1182 // Remove trailing whitespace of the previous line if it was touched. 1183 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) 1184 formatFirstToken(TheLine.First, PreviousLineLastToken, Indent, 1185 TheLine.InPPDirective, PreviousEndOfLineColumn); 1186 } 1187 // If we did not reformat this unwrapped line, the column at the end of 1188 // the last token is unchanged - thus, we can calculate the end of the 1189 // last token. 1190 SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation(); 1191 PreviousEndOfLineColumn = 1192 SourceMgr.getSpellingColumnNumber(LastLoc) + 1193 Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1; 1194 PreviousLineWasTouched = false; 1195 if (TheLine.Last->is(tok::comment)) 1196 Whitespaces.addUntouchableComment( 1197 SourceMgr.getSpellingColumnNumber( 1198 TheLine.Last->FormatTok.Tok.getLocation()) - 1199 1); 1200 else 1201 Whitespaces.alignComments(); 1202 } 1203 PreviousLineLastToken = I->Last; 1204 } 1205 return Whitespaces.generateReplacements(); 1206 } 1207 1208 private: 1209 void deriveLocalStyle() { 1210 unsigned CountBoundToVariable = 0; 1211 unsigned CountBoundToType = 0; 1212 bool HasCpp03IncompatibleFormat = false; 1213 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 1214 if (AnnotatedLines[i].First.Children.empty()) 1215 continue; 1216 AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0]; 1217 while (!Tok->Children.empty()) { 1218 if (Tok->Type == TT_PointerOrReference) { 1219 bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0; 1220 bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0; 1221 if (SpacesBefore && !SpacesAfter) 1222 ++CountBoundToVariable; 1223 else if (!SpacesBefore && SpacesAfter) 1224 ++CountBoundToType; 1225 } 1226 1227 if (Tok->Type == TT_TemplateCloser && 1228 Tok->Parent->Type == TT_TemplateCloser && 1229 Tok->FormatTok.WhiteSpaceLength == 0) 1230 HasCpp03IncompatibleFormat = true; 1231 Tok = &Tok->Children[0]; 1232 } 1233 } 1234 if (Style.DerivePointerBinding) { 1235 if (CountBoundToType > CountBoundToVariable) 1236 Style.PointerBindsToType = true; 1237 else if (CountBoundToType < CountBoundToVariable) 1238 Style.PointerBindsToType = false; 1239 } 1240 if (Style.Standard == FormatStyle::LS_Auto) { 1241 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11 1242 : FormatStyle::LS_Cpp03; 1243 } 1244 } 1245 1246 /// \brief Get the indent of \p Level from \p IndentForLevel. 1247 /// 1248 /// \p IndentForLevel must contain the indent for the level \c l 1249 /// at \p IndentForLevel[l], or a value < 0 if the indent for 1250 /// that level is unknown. 1251 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) { 1252 if (IndentForLevel[Level] != -1) 1253 return IndentForLevel[Level]; 1254 if (Level == 0) 1255 return 0; 1256 return getIndent(IndentForLevel, Level - 1) + 2; 1257 } 1258 1259 /// \brief Get the offset of the line relatively to the level. 1260 /// 1261 /// For example, 'public:' labels in classes are offset by 1 or 2 1262 /// characters to the left from their level. 1263 int getIndentOffset(const AnnotatedToken &RootToken) { 1264 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier()) 1265 return Style.AccessModifierOffset; 1266 return 0; 1267 } 1268 1269 /// \brief Tries to merge lines into one. 1270 /// 1271 /// This will change \c Line and \c AnnotatedLine to contain the merged line, 1272 /// if possible; note that \c I will be incremented when lines are merged. 1273 /// 1274 /// Returns whether the resulting \c Line can fit in a single line. 1275 void tryFitMultipleLinesInOne(unsigned Indent, 1276 std::vector<AnnotatedLine>::iterator &I, 1277 std::vector<AnnotatedLine>::iterator E) { 1278 // We can never merge stuff if there are trailing line comments. 1279 if (I->Last->Type == TT_LineComment) 1280 return; 1281 1282 unsigned Limit = Style.ColumnLimit - Indent; 1283 // If we already exceed the column limit, we set 'Limit' to 0. The different 1284 // tryMerge..() functions can then decide whether to still do merging. 1285 Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength; 1286 1287 if (I + 1 == E || (I + 1)->Type == LT_Invalid) 1288 return; 1289 1290 if (I->Last->is(tok::l_brace)) { 1291 tryMergeSimpleBlock(I, E, Limit); 1292 } else if (I->First.is(tok::kw_if)) { 1293 tryMergeSimpleIf(I, E, Limit); 1294 } else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline || 1295 I->First.FormatTok.IsFirst)) { 1296 tryMergeSimplePPDirective(I, E, Limit); 1297 } 1298 return; 1299 } 1300 1301 void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I, 1302 std::vector<AnnotatedLine>::iterator E, 1303 unsigned Limit) { 1304 if (Limit == 0) 1305 return; 1306 AnnotatedLine &Line = *I; 1307 if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline) 1308 return; 1309 if (I + 2 != E && (I + 2)->InPPDirective && 1310 !(I + 2)->First.FormatTok.HasUnescapedNewline) 1311 return; 1312 if (1 + (I + 1)->Last->TotalLength > Limit) 1313 return; 1314 join(Line, *(++I)); 1315 } 1316 1317 void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I, 1318 std::vector<AnnotatedLine>::iterator E, 1319 unsigned Limit) { 1320 if (Limit == 0) 1321 return; 1322 if (!Style.AllowShortIfStatementsOnASingleLine) 1323 return; 1324 if ((I + 1)->InPPDirective != I->InPPDirective || 1325 ((I + 1)->InPPDirective && 1326 (I + 1)->First.FormatTok.HasUnescapedNewline)) 1327 return; 1328 AnnotatedLine &Line = *I; 1329 if (Line.Last->isNot(tok::r_paren)) 1330 return; 1331 if (1 + (I + 1)->Last->TotalLength > Limit) 1332 return; 1333 if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment) 1334 return; 1335 // Only inline simple if's (no nested if or else). 1336 if (I + 2 != E && (I + 2)->First.is(tok::kw_else)) 1337 return; 1338 join(Line, *(++I)); 1339 } 1340 1341 void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I, 1342 std::vector<AnnotatedLine>::iterator E, 1343 unsigned Limit) { 1344 // First, check that the current line allows merging. This is the case if 1345 // we're not in a control flow statement and the last token is an opening 1346 // brace. 1347 AnnotatedLine &Line = *I; 1348 if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace, 1349 tok::kw_else, tok::kw_try, tok::kw_catch, 1350 tok::kw_for, 1351 // This gets rid of all ObjC @ keywords and methods. 1352 tok::at, tok::minus, tok::plus)) 1353 return; 1354 1355 AnnotatedToken *Tok = &(I + 1)->First; 1356 if (Tok->Children.empty() && Tok->is(tok::r_brace) && 1357 !Tok->MustBreakBefore) { 1358 // We merge empty blocks even if the line exceeds the column limit. 1359 Tok->SpacesRequiredBefore = 0; 1360 Tok->CanBreakBefore = true; 1361 join(Line, *(I + 1)); 1362 I += 1; 1363 } else if (Limit != 0) { 1364 // Check that we still have three lines and they fit into the limit. 1365 if (I + 2 == E || (I + 2)->Type == LT_Invalid || 1366 !nextTwoLinesFitInto(I, Limit)) 1367 return; 1368 1369 // Second, check that the next line does not contain any braces - if it 1370 // does, readability declines when putting it into a single line. 1371 if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore) 1372 return; 1373 do { 1374 if (Tok->isOneOf(tok::l_brace, tok::r_brace)) 1375 return; 1376 Tok = Tok->Children.empty() ? NULL : &Tok->Children.back(); 1377 } while (Tok != NULL); 1378 1379 // Last, check that the third line contains a single closing brace. 1380 Tok = &(I + 2)->First; 1381 if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) || 1382 Tok->MustBreakBefore) 1383 return; 1384 1385 join(Line, *(I + 1)); 1386 join(Line, *(I + 2)); 1387 I += 2; 1388 } 1389 } 1390 1391 bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I, 1392 unsigned Limit) { 1393 return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <= 1394 Limit; 1395 } 1396 1397 void join(AnnotatedLine &A, const AnnotatedLine &B) { 1398 unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore; 1399 A.Last->Children.push_back(B.First); 1400 while (!A.Last->Children.empty()) { 1401 A.Last->Children[0].Parent = A.Last; 1402 A.Last->Children[0].TotalLength += LengthA; 1403 A.Last = &A.Last->Children[0]; 1404 } 1405 } 1406 1407 bool touchesRanges(const CharSourceRange &Range) { 1408 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { 1409 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), 1410 Ranges[i].getBegin()) && 1411 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(), 1412 Range.getBegin())) 1413 return true; 1414 } 1415 return false; 1416 } 1417 1418 bool touchesLine(const AnnotatedLine &TheLine) { 1419 const FormatToken *First = &TheLine.First.FormatTok; 1420 const FormatToken *Last = &TheLine.Last->FormatTok; 1421 CharSourceRange LineRange = CharSourceRange::getTokenRange( 1422 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset), 1423 Last->Tok.getLocation()); 1424 return touchesRanges(LineRange); 1425 } 1426 1427 bool touchesPPDirective(std::vector<AnnotatedLine>::iterator I, 1428 std::vector<AnnotatedLine>::iterator E) { 1429 for (; I != E; ++I) { 1430 if (I->First.FormatTok.HasUnescapedNewline) 1431 return false; 1432 if (touchesLine(*I)) 1433 return true; 1434 } 1435 return false; 1436 } 1437 1438 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) { 1439 const FormatToken *First = &TheLine.First.FormatTok; 1440 CharSourceRange LineRange = CharSourceRange::getCharRange( 1441 First->WhiteSpaceStart, 1442 First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset)); 1443 return touchesRanges(LineRange); 1444 } 1445 1446 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) { 1447 AnnotatedLines.push_back(AnnotatedLine(TheLine)); 1448 } 1449 1450 /// \brief Add a new line and the required indent before the first Token 1451 /// of the \c UnwrappedLine if there was no structural parsing error. 1452 /// Returns the indent level of the \c UnwrappedLine. 1453 void formatFirstToken(const AnnotatedToken &RootToken, 1454 const AnnotatedToken *PreviousToken, unsigned Indent, 1455 bool InPPDirective, unsigned PreviousEndOfLineColumn) { 1456 const FormatToken &Tok = RootToken.FormatTok; 1457 1458 unsigned Newlines = 1459 std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 1460 if (Newlines == 0 && !Tok.IsFirst) 1461 Newlines = 1; 1462 1463 if (!InPPDirective || Tok.HasUnescapedNewline) { 1464 // Insert extra new line before access specifiers. 1465 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) && 1466 RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1) 1467 ++Newlines; 1468 1469 Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0); 1470 } else { 1471 Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent, 1472 PreviousEndOfLineColumn); 1473 } 1474 } 1475 1476 DiagnosticsEngine &Diag; 1477 FormatStyle Style; 1478 Lexer &Lex; 1479 SourceManager &SourceMgr; 1480 WhitespaceManager Whitespaces; 1481 std::vector<CharSourceRange> Ranges; 1482 std::vector<AnnotatedLine> AnnotatedLines; 1483 }; 1484 1485 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex, 1486 SourceManager &SourceMgr, 1487 std::vector<CharSourceRange> Ranges, 1488 DiagnosticConsumer *DiagClient) { 1489 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); 1490 OwningPtr<DiagnosticConsumer> DiagPrinter; 1491 if (DiagClient == 0) { 1492 DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts)); 1493 DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP()); 1494 DiagClient = DiagPrinter.get(); 1495 } 1496 DiagnosticsEngine Diagnostics( 1497 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, 1498 DiagClient, false); 1499 Diagnostics.setSourceManager(&SourceMgr); 1500 Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges); 1501 return formatter.format(); 1502 } 1503 1504 LangOptions getFormattingLangOpts() { 1505 LangOptions LangOpts; 1506 LangOpts.CPlusPlus = 1; 1507 LangOpts.CPlusPlus11 = 1; 1508 LangOpts.LineComment = 1; 1509 LangOpts.Bool = 1; 1510 LangOpts.ObjC1 = 1; 1511 LangOpts.ObjC2 = 1; 1512 return LangOpts; 1513 } 1514 1515 } // namespace format 1516 } // namespace clang 1517