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