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 "ContinuationIndenter.h" 19 #include "TokenAnnotator.h" 20 #include "UnwrappedLineParser.h" 21 #include "WhitespaceManager.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/SourceManager.h" 24 #include "clang/Format/Format.h" 25 #include "clang/Lex/Lexer.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/Support/Allocator.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/YAMLTraits.h" 30 #include <queue> 31 #include <string> 32 33 namespace llvm { 34 namespace yaml { 35 template <> 36 struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> { 37 static void enumeration(IO &IO, 38 clang::format::FormatStyle::LanguageStandard &Value) { 39 IO.enumCase(Value, "Cpp03", clang::format::FormatStyle::LS_Cpp03); 40 IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03); 41 IO.enumCase(Value, "Cpp11", clang::format::FormatStyle::LS_Cpp11); 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 <> 48 struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> { 49 static void 50 enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) { 51 IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach); 52 IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux); 53 IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup); 54 IO.enumCase(Value, "Allman", clang::format::FormatStyle::BS_Allman); 55 } 56 }; 57 58 template <> 59 struct ScalarEnumerationTraits< 60 clang::format::FormatStyle::NamespaceIndentationKind> { 61 static void 62 enumeration(IO &IO, 63 clang::format::FormatStyle::NamespaceIndentationKind &Value) { 64 IO.enumCase(Value, "None", clang::format::FormatStyle::NI_None); 65 IO.enumCase(Value, "Inner", clang::format::FormatStyle::NI_Inner); 66 IO.enumCase(Value, "All", clang::format::FormatStyle::NI_All); 67 } 68 }; 69 70 template <> struct MappingTraits<clang::format::FormatStyle> { 71 static void mapping(llvm::yaml::IO &IO, clang::format::FormatStyle &Style) { 72 if (IO.outputting()) { 73 StringRef StylesArray[] = { "LLVM", "Google", "Chromium", 74 "Mozilla", "WebKit" }; 75 ArrayRef<StringRef> Styles(StylesArray); 76 for (size_t i = 0, e = Styles.size(); i < e; ++i) { 77 StringRef StyleName(Styles[i]); 78 clang::format::FormatStyle PredefinedStyle; 79 if (clang::format::getPredefinedStyle(StyleName, &PredefinedStyle) && 80 Style == PredefinedStyle) { 81 IO.mapOptional("# BasedOnStyle", StyleName); 82 break; 83 } 84 } 85 } else { 86 StringRef BasedOnStyle; 87 IO.mapOptional("BasedOnStyle", BasedOnStyle); 88 if (!BasedOnStyle.empty()) 89 if (!clang::format::getPredefinedStyle(BasedOnStyle, &Style)) { 90 IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle)); 91 return; 92 } 93 } 94 95 IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset); 96 IO.mapOptional("ConstructorInitializerIndentWidth", 97 Style.ConstructorInitializerIndentWidth); 98 IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft); 99 IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments); 100 IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", 101 Style.AllowAllParametersOfDeclarationOnNextLine); 102 IO.mapOptional("AllowShortIfStatementsOnASingleLine", 103 Style.AllowShortIfStatementsOnASingleLine); 104 IO.mapOptional("AllowShortLoopsOnASingleLine", 105 Style.AllowShortLoopsOnASingleLine); 106 IO.mapOptional("AlwaysBreakTemplateDeclarations", 107 Style.AlwaysBreakTemplateDeclarations); 108 IO.mapOptional("AlwaysBreakBeforeMultilineStrings", 109 Style.AlwaysBreakBeforeMultilineStrings); 110 IO.mapOptional("BreakBeforeBinaryOperators", 111 Style.BreakBeforeBinaryOperators); 112 IO.mapOptional("BreakConstructorInitializersBeforeComma", 113 Style.BreakConstructorInitializersBeforeComma); 114 IO.mapOptional("BinPackParameters", Style.BinPackParameters); 115 IO.mapOptional("ColumnLimit", Style.ColumnLimit); 116 IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", 117 Style.ConstructorInitializerAllOnOneLineOrOnePerLine); 118 IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding); 119 IO.mapOptional("ExperimentalAutoDetectBinPacking", 120 Style.ExperimentalAutoDetectBinPacking); 121 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels); 122 IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep); 123 IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation); 124 IO.mapOptional("ObjCSpaceBeforeProtocolList", 125 Style.ObjCSpaceBeforeProtocolList); 126 IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment); 127 IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString); 128 IO.mapOptional("PenaltyBreakFirstLessLess", 129 Style.PenaltyBreakFirstLessLess); 130 IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter); 131 IO.mapOptional("PenaltyReturnTypeOnItsOwnLine", 132 Style.PenaltyReturnTypeOnItsOwnLine); 133 IO.mapOptional("PointerBindsToType", Style.PointerBindsToType); 134 IO.mapOptional("SpacesBeforeTrailingComments", 135 Style.SpacesBeforeTrailingComments); 136 IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle); 137 IO.mapOptional("Standard", Style.Standard); 138 IO.mapOptional("IndentWidth", Style.IndentWidth); 139 IO.mapOptional("TabWidth", Style.TabWidth); 140 IO.mapOptional("UseTab", Style.UseTab); 141 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces); 142 IO.mapOptional("IndentFunctionDeclarationAfterType", 143 Style.IndentFunctionDeclarationAfterType); 144 IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses); 145 IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses); 146 IO.mapOptional("SpacesInCStyleCastParentheses", 147 Style.SpacesInCStyleCastParentheses); 148 IO.mapOptional("SpaceAfterControlStatementKeyword", 149 Style.SpaceAfterControlStatementKeyword); 150 IO.mapOptional("SpaceBeforeAssignmentOperators", 151 Style.SpaceBeforeAssignmentOperators); 152 } 153 }; 154 } 155 } 156 157 namespace clang { 158 namespace format { 159 160 void setDefaultPenalties(FormatStyle &Style) { 161 Style.PenaltyBreakComment = 60; 162 Style.PenaltyBreakFirstLessLess = 120; 163 Style.PenaltyBreakString = 1000; 164 Style.PenaltyExcessCharacter = 1000000; 165 } 166 167 FormatStyle getLLVMStyle() { 168 FormatStyle LLVMStyle; 169 LLVMStyle.AccessModifierOffset = -2; 170 LLVMStyle.AlignEscapedNewlinesLeft = false; 171 LLVMStyle.AlignTrailingComments = true; 172 LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; 173 LLVMStyle.AllowShortIfStatementsOnASingleLine = false; 174 LLVMStyle.AllowShortLoopsOnASingleLine = false; 175 LLVMStyle.AlwaysBreakBeforeMultilineStrings = false; 176 LLVMStyle.AlwaysBreakTemplateDeclarations = false; 177 LLVMStyle.BinPackParameters = true; 178 LLVMStyle.BreakBeforeBinaryOperators = false; 179 LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach; 180 LLVMStyle.BreakConstructorInitializersBeforeComma = false; 181 LLVMStyle.ColumnLimit = 80; 182 LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 183 LLVMStyle.ConstructorInitializerIndentWidth = 4; 184 LLVMStyle.Cpp11BracedListStyle = false; 185 LLVMStyle.DerivePointerBinding = false; 186 LLVMStyle.ExperimentalAutoDetectBinPacking = false; 187 LLVMStyle.IndentCaseLabels = false; 188 LLVMStyle.IndentFunctionDeclarationAfterType = false; 189 LLVMStyle.IndentWidth = 2; 190 LLVMStyle.TabWidth = 8; 191 LLVMStyle.MaxEmptyLinesToKeep = 1; 192 LLVMStyle.NamespaceIndentation = FormatStyle::NI_None; 193 LLVMStyle.ObjCSpaceBeforeProtocolList = true; 194 LLVMStyle.PointerBindsToType = false; 195 LLVMStyle.SpacesBeforeTrailingComments = 1; 196 LLVMStyle.Standard = FormatStyle::LS_Cpp03; 197 LLVMStyle.UseTab = false; 198 LLVMStyle.SpacesInParentheses = false; 199 LLVMStyle.SpaceInEmptyParentheses = false; 200 LLVMStyle.SpacesInCStyleCastParentheses = false; 201 LLVMStyle.SpaceAfterControlStatementKeyword = true; 202 LLVMStyle.SpaceBeforeAssignmentOperators = true; 203 204 setDefaultPenalties(LLVMStyle); 205 LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60; 206 207 return LLVMStyle; 208 } 209 210 FormatStyle getGoogleStyle() { 211 FormatStyle GoogleStyle; 212 GoogleStyle.AccessModifierOffset = -1; 213 GoogleStyle.AlignEscapedNewlinesLeft = true; 214 GoogleStyle.AlignTrailingComments = true; 215 GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true; 216 GoogleStyle.AllowShortIfStatementsOnASingleLine = true; 217 GoogleStyle.AllowShortLoopsOnASingleLine = true; 218 GoogleStyle.AlwaysBreakBeforeMultilineStrings = true; 219 GoogleStyle.AlwaysBreakTemplateDeclarations = true; 220 GoogleStyle.BinPackParameters = true; 221 GoogleStyle.BreakBeforeBinaryOperators = false; 222 GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach; 223 GoogleStyle.BreakConstructorInitializersBeforeComma = false; 224 GoogleStyle.ColumnLimit = 80; 225 GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 226 GoogleStyle.ConstructorInitializerIndentWidth = 4; 227 GoogleStyle.Cpp11BracedListStyle = true; 228 GoogleStyle.DerivePointerBinding = true; 229 GoogleStyle.ExperimentalAutoDetectBinPacking = false; 230 GoogleStyle.IndentCaseLabels = true; 231 GoogleStyle.IndentFunctionDeclarationAfterType = true; 232 GoogleStyle.IndentWidth = 2; 233 GoogleStyle.TabWidth = 8; 234 GoogleStyle.MaxEmptyLinesToKeep = 1; 235 GoogleStyle.NamespaceIndentation = FormatStyle::NI_None; 236 GoogleStyle.ObjCSpaceBeforeProtocolList = false; 237 GoogleStyle.PointerBindsToType = true; 238 GoogleStyle.SpacesBeforeTrailingComments = 2; 239 GoogleStyle.Standard = FormatStyle::LS_Auto; 240 GoogleStyle.UseTab = false; 241 GoogleStyle.SpacesInParentheses = false; 242 GoogleStyle.SpaceInEmptyParentheses = false; 243 GoogleStyle.SpacesInCStyleCastParentheses = false; 244 GoogleStyle.SpaceAfterControlStatementKeyword = true; 245 GoogleStyle.SpaceBeforeAssignmentOperators = true; 246 247 setDefaultPenalties(GoogleStyle); 248 GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200; 249 250 return GoogleStyle; 251 } 252 253 FormatStyle getChromiumStyle() { 254 FormatStyle ChromiumStyle = getGoogleStyle(); 255 ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; 256 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false; 257 ChromiumStyle.AllowShortLoopsOnASingleLine = false; 258 ChromiumStyle.BinPackParameters = false; 259 ChromiumStyle.DerivePointerBinding = false; 260 ChromiumStyle.Standard = FormatStyle::LS_Cpp03; 261 return ChromiumStyle; 262 } 263 264 FormatStyle getMozillaStyle() { 265 FormatStyle MozillaStyle = getLLVMStyle(); 266 MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false; 267 MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; 268 MozillaStyle.DerivePointerBinding = true; 269 MozillaStyle.IndentCaseLabels = true; 270 MozillaStyle.ObjCSpaceBeforeProtocolList = false; 271 MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; 272 MozillaStyle.PointerBindsToType = true; 273 return MozillaStyle; 274 } 275 276 FormatStyle getWebKitStyle() { 277 FormatStyle Style = getLLVMStyle(); 278 Style.AccessModifierOffset = -4; 279 Style.AlignTrailingComments = false; 280 Style.BreakBeforeBinaryOperators = true; 281 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 282 Style.BreakConstructorInitializersBeforeComma = true; 283 Style.ColumnLimit = 0; 284 Style.IndentWidth = 4; 285 Style.NamespaceIndentation = FormatStyle::NI_Inner; 286 Style.PointerBindsToType = true; 287 return Style; 288 } 289 290 bool getPredefinedStyle(StringRef Name, FormatStyle *Style) { 291 if (Name.equals_lower("llvm")) 292 *Style = getLLVMStyle(); 293 else if (Name.equals_lower("chromium")) 294 *Style = getChromiumStyle(); 295 else if (Name.equals_lower("mozilla")) 296 *Style = getMozillaStyle(); 297 else if (Name.equals_lower("google")) 298 *Style = getGoogleStyle(); 299 else if (Name.equals_lower("webkit")) 300 *Style = getWebKitStyle(); 301 else 302 return false; 303 304 return true; 305 } 306 307 llvm::error_code parseConfiguration(StringRef Text, FormatStyle *Style) { 308 if (Text.trim().empty()) 309 return llvm::make_error_code(llvm::errc::invalid_argument); 310 llvm::yaml::Input Input(Text); 311 Input >> *Style; 312 return Input.error(); 313 } 314 315 std::string configurationAsText(const FormatStyle &Style) { 316 std::string Text; 317 llvm::raw_string_ostream Stream(Text); 318 llvm::yaml::Output Output(Stream); 319 // We use the same mapping method for input and output, so we need a non-const 320 // reference here. 321 FormatStyle NonConstStyle = Style; 322 Output << NonConstStyle; 323 return Stream.str(); 324 } 325 326 namespace { 327 328 class NoColumnLimitFormatter { 329 public: 330 NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {} 331 332 /// \brief Formats the line starting at \p State, simply keeping all of the 333 /// input's line breaking decisions. 334 void format(unsigned FirstIndent, const AnnotatedLine *Line) { 335 LineState State = 336 Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false); 337 while (State.NextToken != NULL) { 338 bool Newline = 339 Indenter->mustBreak(State) || 340 (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); 341 Indenter->addTokenToState(State, Newline, /*DryRun=*/false); 342 } 343 } 344 345 private: 346 ContinuationIndenter *Indenter; 347 }; 348 349 class UnwrappedLineFormatter { 350 public: 351 UnwrappedLineFormatter(ContinuationIndenter *Indenter, 352 WhitespaceManager *Whitespaces, 353 const FormatStyle &Style, const AnnotatedLine &Line) 354 : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Line(Line), 355 Count(0) {} 356 357 /// \brief Formats an \c UnwrappedLine and returns the penalty. 358 /// 359 /// If \p DryRun is \c false, directly applies the changes. 360 unsigned format(unsigned FirstIndent, bool DryRun = false) { 361 LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun); 362 363 // If the ObjC method declaration does not fit on a line, we should format 364 // it with one arg per line. 365 if (Line.Type == LT_ObjCMethodDecl) 366 State.Stack.back().BreakBeforeParameter = true; 367 368 // Find best solution in solution space. 369 return analyzeSolutionSpace(State, DryRun); 370 } 371 372 private: 373 /// \brief An edge in the solution space from \c Previous->State to \c State, 374 /// inserting a newline dependent on the \c NewLine. 375 struct StateNode { 376 StateNode(const LineState &State, bool NewLine, StateNode *Previous) 377 : State(State), NewLine(NewLine), Previous(Previous) {} 378 LineState State; 379 bool NewLine; 380 StateNode *Previous; 381 }; 382 383 /// \brief A pair of <penalty, count> that is used to prioritize the BFS on. 384 /// 385 /// In case of equal penalties, we want to prefer states that were inserted 386 /// first. During state generation we make sure that we insert states first 387 /// that break the line as late as possible. 388 typedef std::pair<unsigned, unsigned> OrderedPenalty; 389 390 /// \brief An item in the prioritized BFS search queue. The \c StateNode's 391 /// \c State has the given \c OrderedPenalty. 392 typedef std::pair<OrderedPenalty, StateNode *> QueueItem; 393 394 /// \brief The BFS queue type. 395 typedef std::priority_queue<QueueItem, std::vector<QueueItem>, 396 std::greater<QueueItem> > QueueType; 397 398 /// \brief Analyze the entire solution space starting from \p InitialState. 399 /// 400 /// This implements a variant of Dijkstra's algorithm on the graph that spans 401 /// the solution space (\c LineStates are the nodes). The algorithm tries to 402 /// find the shortest path (the one with lowest penalty) from \p InitialState 403 /// to a state where all tokens are placed. Returns the penalty. 404 /// 405 /// If \p DryRun is \c false, directly applies the changes. 406 unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) { 407 std::set<LineState> Seen; 408 409 // Insert start element into queue. 410 StateNode *Node = 411 new (Allocator.Allocate()) StateNode(InitialState, false, NULL); 412 Queue.push(QueueItem(OrderedPenalty(0, Count), Node)); 413 ++Count; 414 415 unsigned Penalty = 0; 416 417 // While not empty, take first element and follow edges. 418 while (!Queue.empty()) { 419 Penalty = Queue.top().first.first; 420 StateNode *Node = Queue.top().second; 421 if (Node->State.NextToken == NULL) { 422 DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n"); 423 break; 424 } 425 Queue.pop(); 426 427 // Cut off the analysis of certain solutions if the analysis gets too 428 // complex. See description of IgnoreStackForComparison. 429 if (Count > 10000) 430 Node->State.IgnoreStackForComparison = true; 431 432 if (!Seen.insert(Node->State).second) 433 // State already examined with lower penalty. 434 continue; 435 436 addNextStateToQueue(Penalty, Node, /*NewLine=*/false); 437 addNextStateToQueue(Penalty, Node, /*NewLine=*/true); 438 } 439 440 if (Queue.empty()) 441 // We were unable to find a solution, do nothing. 442 // FIXME: Add diagnostic? 443 return 0; 444 445 // Reconstruct the solution. 446 if (!DryRun) 447 reconstructPath(InitialState, Queue.top().second); 448 449 DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n"); 450 DEBUG(llvm::dbgs() << "---\n"); 451 452 return Penalty; 453 } 454 455 void reconstructPath(LineState &State, StateNode *Current) { 456 std::deque<StateNode *> Path; 457 // We do not need a break before the initial token. 458 while (Current->Previous) { 459 Path.push_front(Current); 460 Current = Current->Previous; 461 } 462 for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end(); 463 I != E; ++I) { 464 unsigned Penalty = 0; 465 formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty); 466 Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false); 467 468 DEBUG({ 469 if ((*I)->NewLine) { 470 llvm::dbgs() << "Penalty for placing " 471 << (*I)->Previous->State.NextToken->Tok.getName() << ": " 472 << Penalty << "\n"; 473 } 474 }); 475 } 476 } 477 478 /// \brief Add the following state to the analysis queue \c Queue. 479 /// 480 /// Assume the current state is \p PreviousNode and has been reached with a 481 /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. 482 void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, 483 bool NewLine) { 484 if (NewLine && !Indenter->canBreak(PreviousNode->State)) 485 return; 486 if (!NewLine && Indenter->mustBreak(PreviousNode->State)) 487 return; 488 489 StateNode *Node = new (Allocator.Allocate()) 490 StateNode(PreviousNode->State, NewLine, PreviousNode); 491 if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty)) 492 return; 493 494 Penalty += Indenter->addTokenToState(Node->State, NewLine, true); 495 496 Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node)); 497 ++Count; 498 } 499 500 /// \brief If the \p State's next token is an r_brace closing a nested block, 501 /// format the nested block before it. 502 /// 503 /// Returns \c true if all children could be placed successfully and adapts 504 /// \p Penalty as well as \p State. If \p DryRun is false, also directly 505 /// creates changes using \c Whitespaces. 506 /// 507 /// The crucial idea here is that children always get formatted upon 508 /// encountering the closing brace right after the nested block. Now, if we 509 /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is 510 /// \c false), the entire block has to be kept on the same line (which is only 511 /// possible if it fits on the line, only contains a single statement, etc. 512 /// 513 /// If \p NewLine is true, we format the nested block on separate lines, i.e. 514 /// break after the "{", format all lines with correct indentation and the put 515 /// the closing "}" on yet another new line. 516 /// 517 /// This enables us to keep the simple structure of the 518 /// \c UnwrappedLineFormatter, where we only have two options for each token: 519 /// break or don't break. 520 bool formatChildren(LineState &State, bool NewLine, bool DryRun, 521 unsigned &Penalty) { 522 const FormatToken &LBrace = *State.NextToken->Previous; 523 if (LBrace.isNot(tok::l_brace) || LBrace.BlockKind != BK_Block || 524 LBrace.Children.size() == 0) 525 // The previous token does not open a block. Nothing to do. We don't 526 // assert so that we can simply call this function for all tokens. 527 return true; 528 529 if (NewLine) { 530 unsigned ParentIndent = State.Stack.back().Indent; 531 for (SmallVector<AnnotatedLine *, 1>::const_iterator 532 I = LBrace.Children.begin(), 533 E = LBrace.Children.end(); 534 I != E; ++I) { 535 unsigned Indent = 536 ParentIndent + ((*I)->Level - Line.Level - 1) * Style.IndentWidth; 537 if (!DryRun) { 538 unsigned Newlines = std::min((*I)->First->NewlinesBefore, 539 Style.MaxEmptyLinesToKeep + 1); 540 Newlines = std::max(1u, Newlines); 541 Whitespaces->replaceWhitespace( 542 *(*I)->First, Newlines, /*Spaces=*/Indent, 543 /*StartOfTokenColumn=*/Indent, Line.InPPDirective); 544 } 545 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, **I); 546 Penalty += Formatter.format(Indent, DryRun); 547 } 548 return true; 549 } 550 551 if (LBrace.Children.size() > 1) 552 return false; // Cannot merge multiple statements into a single line. 553 554 // We can't put the closing "}" on a line with a trailing comment. 555 if (LBrace.Children[0]->Last->isTrailingComment()) 556 return false; 557 558 if (!DryRun) { 559 Whitespaces->replaceWhitespace(*LBrace.Children[0]->First, 560 /*Newlines=*/0, /*Spaces=*/1, 561 /*StartOfTokenColumn=*/State.Column, 562 State.Line->InPPDirective); 563 UnwrappedLineFormatter Formatter(Indenter, Whitespaces, Style, 564 *LBrace.Children[0]); 565 Penalty += Formatter.format(State.Column + 1, DryRun); 566 } 567 568 State.Column += 1 + LBrace.Children[0]->Last->TotalLength; 569 return true; 570 } 571 572 ContinuationIndenter *Indenter; 573 WhitespaceManager *Whitespaces; 574 FormatStyle Style; 575 const AnnotatedLine &Line; 576 577 llvm::SpecificBumpPtrAllocator<StateNode> Allocator; 578 QueueType Queue; 579 // Increasing count of \c StateNode items we have created. This is used 580 // to create a deterministic order independent of the container. 581 unsigned Count; 582 }; 583 584 class FormatTokenLexer { 585 public: 586 FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style, 587 encoding::Encoding Encoding) 588 : FormatTok(NULL), GreaterStashed(false), Column(0), 589 TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr), Style(Style), 590 IdentTable(getFormattingLangOpts()), Encoding(Encoding) { 591 Lex.SetKeepWhitespaceMode(true); 592 } 593 594 ArrayRef<FormatToken *> lex() { 595 assert(Tokens.empty()); 596 do { 597 Tokens.push_back(getNextToken()); 598 maybeJoinPreviousTokens(); 599 } while (Tokens.back()->Tok.isNot(tok::eof)); 600 return Tokens; 601 } 602 603 IdentifierTable &getIdentTable() { return IdentTable; } 604 605 private: 606 void maybeJoinPreviousTokens() { 607 if (Tokens.size() < 4) 608 return; 609 FormatToken *Last = Tokens.back(); 610 if (!Last->is(tok::r_paren)) 611 return; 612 613 FormatToken *String = Tokens[Tokens.size() - 2]; 614 if (!String->is(tok::string_literal) || String->IsMultiline) 615 return; 616 617 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren)) 618 return; 619 620 FormatToken *Macro = Tokens[Tokens.size() - 4]; 621 if (Macro->TokenText != "_T") 622 return; 623 624 const char *Start = Macro->TokenText.data(); 625 const char *End = Last->TokenText.data() + Last->TokenText.size(); 626 String->TokenText = StringRef(Start, End - Start); 627 String->IsFirst = Macro->IsFirst; 628 String->LastNewlineOffset = Macro->LastNewlineOffset; 629 String->WhitespaceRange = Macro->WhitespaceRange; 630 String->OriginalColumn = Macro->OriginalColumn; 631 String->ColumnWidth = encoding::columnWidthWithTabs( 632 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding); 633 634 Tokens.pop_back(); 635 Tokens.pop_back(); 636 Tokens.pop_back(); 637 Tokens.back() = String; 638 } 639 640 FormatToken *getNextToken() { 641 if (GreaterStashed) { 642 // Create a synthesized second '>' token. 643 // FIXME: Increment Column and set OriginalColumn. 644 Token Greater = FormatTok->Tok; 645 FormatTok = new (Allocator.Allocate()) FormatToken; 646 FormatTok->Tok = Greater; 647 SourceLocation GreaterLocation = 648 FormatTok->Tok.getLocation().getLocWithOffset(1); 649 FormatTok->WhitespaceRange = 650 SourceRange(GreaterLocation, GreaterLocation); 651 FormatTok->TokenText = ">"; 652 FormatTok->ColumnWidth = 1; 653 GreaterStashed = false; 654 return FormatTok; 655 } 656 657 FormatTok = new (Allocator.Allocate()) FormatToken; 658 readRawToken(*FormatTok); 659 SourceLocation WhitespaceStart = 660 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace); 661 if (SourceMgr.getFileOffset(WhitespaceStart) == 0) 662 FormatTok->IsFirst = true; 663 664 // Consume and record whitespace until we find a significant token. 665 unsigned WhitespaceLength = TrailingWhitespace; 666 while (FormatTok->Tok.is(tok::unknown)) { 667 for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) { 668 switch (FormatTok->TokenText[i]) { 669 case '\n': 670 ++FormatTok->NewlinesBefore; 671 // FIXME: This is technically incorrect, as it could also 672 // be a literal backslash at the end of the line. 673 if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' && 674 (FormatTok->TokenText[i - 1] != '\r' || i == 1 || 675 FormatTok->TokenText[i - 2] != '\\'))) 676 FormatTok->HasUnescapedNewline = true; 677 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1; 678 Column = 0; 679 break; 680 case ' ': 681 ++Column; 682 break; 683 case '\t': 684 Column += Style.TabWidth - Column % Style.TabWidth; 685 break; 686 default: 687 ++Column; 688 break; 689 } 690 } 691 692 WhitespaceLength += FormatTok->Tok.getLength(); 693 694 readRawToken(*FormatTok); 695 } 696 697 // In case the token starts with escaped newlines, we want to 698 // take them into account as whitespace - this pattern is quite frequent 699 // in macro definitions. 700 // FIXME: Add a more explicit test. 701 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' && 702 FormatTok->TokenText[1] == '\n') { 703 // FIXME: ++FormatTok->NewlinesBefore is missing... 704 WhitespaceLength += 2; 705 Column = 0; 706 FormatTok->TokenText = FormatTok->TokenText.substr(2); 707 } 708 709 FormatTok->WhitespaceRange = SourceRange( 710 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength)); 711 712 FormatTok->OriginalColumn = Column; 713 714 TrailingWhitespace = 0; 715 if (FormatTok->Tok.is(tok::comment)) { 716 // FIXME: Add the trimmed whitespace to Column. 717 StringRef UntrimmedText = FormatTok->TokenText; 718 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f"); 719 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size(); 720 } else if (FormatTok->Tok.is(tok::raw_identifier)) { 721 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText); 722 FormatTok->Tok.setIdentifierInfo(&Info); 723 FormatTok->Tok.setKind(Info.getTokenID()); 724 } else if (FormatTok->Tok.is(tok::greatergreater)) { 725 FormatTok->Tok.setKind(tok::greater); 726 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1); 727 GreaterStashed = true; 728 } 729 730 // Now FormatTok is the next non-whitespace token. 731 732 StringRef Text = FormatTok->TokenText; 733 size_t FirstNewlinePos = Text.find('\n'); 734 if (FirstNewlinePos == StringRef::npos) { 735 // FIXME: ColumnWidth actually depends on the start column, we need to 736 // take this into account when the token is moved. 737 FormatTok->ColumnWidth = 738 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding); 739 Column += FormatTok->ColumnWidth; 740 } else { 741 FormatTok->IsMultiline = true; 742 // FIXME: ColumnWidth actually depends on the start column, we need to 743 // take this into account when the token is moved. 744 FormatTok->ColumnWidth = encoding::columnWidthWithTabs( 745 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding); 746 747 // The last line of the token always starts in column 0. 748 // Thus, the length can be precomputed even in the presence of tabs. 749 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs( 750 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, 751 Encoding); 752 Column = FormatTok->LastLineColumnWidth; 753 } 754 755 return FormatTok; 756 } 757 758 FormatToken *FormatTok; 759 bool GreaterStashed; 760 unsigned Column; 761 unsigned TrailingWhitespace; 762 Lexer &Lex; 763 SourceManager &SourceMgr; 764 FormatStyle &Style; 765 IdentifierTable IdentTable; 766 encoding::Encoding Encoding; 767 llvm::SpecificBumpPtrAllocator<FormatToken> Allocator; 768 SmallVector<FormatToken *, 16> Tokens; 769 770 void readRawToken(FormatToken &Tok) { 771 Lex.LexFromRawLexer(Tok.Tok); 772 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()), 773 Tok.Tok.getLength()); 774 // For formatting, treat unterminated string literals like normal string 775 // literals. 776 if (Tok.is(tok::unknown) && !Tok.TokenText.empty() && 777 Tok.TokenText[0] == '"') { 778 Tok.Tok.setKind(tok::string_literal); 779 Tok.IsUnterminatedLiteral = true; 780 } 781 } 782 }; 783 784 class Formatter : public UnwrappedLineConsumer { 785 public: 786 Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr, 787 const std::vector<CharSourceRange> &Ranges) 788 : Style(Style), Lex(Lex), SourceMgr(SourceMgr), 789 Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())), 790 Ranges(Ranges), Encoding(encoding::detectEncoding(Lex.getBuffer())) { 791 DEBUG(llvm::dbgs() << "File encoding: " 792 << (Encoding == encoding::Encoding_UTF8 ? "UTF8" 793 : "unknown") 794 << "\n"); 795 } 796 797 virtual ~Formatter() { 798 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 799 delete AnnotatedLines[i]; 800 } 801 } 802 803 tooling::Replacements format() { 804 FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding); 805 806 UnwrappedLineParser Parser(Style, Tokens.lex(), *this); 807 bool StructuralError = Parser.parse(); 808 TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in")); 809 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 810 Annotator.annotate(*AnnotatedLines[i]); 811 } 812 deriveLocalStyle(); 813 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 814 Annotator.calculateFormattingInformation(*AnnotatedLines[i]); 815 } 816 817 Annotator.setCommentLineLevels(AnnotatedLines); 818 819 std::vector<int> IndentForLevel; 820 bool PreviousLineWasTouched = false; 821 const FormatToken *PreviousLineLastToken = 0; 822 bool FormatPPDirective = false; 823 for (SmallVectorImpl<AnnotatedLine *>::iterator I = AnnotatedLines.begin(), 824 E = AnnotatedLines.end(); 825 I != E; ++I) { 826 const AnnotatedLine &TheLine = **I; 827 const FormatToken *FirstTok = TheLine.First; 828 int Offset = getIndentOffset(*TheLine.First); 829 830 // Check whether this line is part of a formatted preprocessor directive. 831 if (FirstTok->HasUnescapedNewline) 832 FormatPPDirective = false; 833 if (!FormatPPDirective && TheLine.InPPDirective && 834 (touchesLine(TheLine) || touchesPPDirective(I + 1, E))) 835 FormatPPDirective = true; 836 837 // Determine indent and try to merge multiple unwrapped lines. 838 while (IndentForLevel.size() <= TheLine.Level) 839 IndentForLevel.push_back(-1); 840 IndentForLevel.resize(TheLine.Level + 1); 841 unsigned Indent = getIndent(IndentForLevel, TheLine.Level); 842 if (static_cast<int>(Indent) + Offset >= 0) 843 Indent += Offset; 844 tryFitMultipleLinesInOne(Indent, I, E); 845 846 bool WasMoved = PreviousLineWasTouched && FirstTok->NewlinesBefore == 0; 847 if (TheLine.First->is(tok::eof)) { 848 if (PreviousLineWasTouched) { 849 unsigned NewLines = std::min(FirstTok->NewlinesBefore, 1u); 850 Whitespaces.replaceWhitespace(*TheLine.First, NewLines, /*Indent*/ 0, 851 /*TargetColumn*/ 0); 852 } 853 } else if (TheLine.Type != LT_Invalid && 854 (WasMoved || FormatPPDirective || touchesLine(TheLine))) { 855 unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level); 856 if (FirstTok->WhitespaceRange.isValid() && 857 // Insert a break even if there is a structural error in case where 858 // we break apart a line consisting of multiple unwrapped lines. 859 (FirstTok->NewlinesBefore == 0 || !StructuralError)) { 860 formatFirstToken(*TheLine.First, PreviousLineLastToken, Indent, 861 TheLine.InPPDirective); 862 } else { 863 Indent = LevelIndent = FirstTok->OriginalColumn; 864 } 865 ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding, 866 BinPackInconclusiveFunctions); 867 868 // If everything fits on a single line, just put it there. 869 unsigned ColumnLimit = Style.ColumnLimit; 870 AnnotatedLine *NextLine = *(I + 1); 871 if ((I + 1) != E && NextLine->InPPDirective && 872 !NextLine->First->HasUnescapedNewline) 873 ColumnLimit = getColumnLimit(TheLine.InPPDirective); 874 875 if (TheLine.Last->TotalLength + Indent <= ColumnLimit) { 876 LineState State = 877 Indenter.getInitialState(Indent, &TheLine, /*DryRun=*/false); 878 while (State.NextToken != NULL) 879 Indenter.addTokenToState(State, false, false); 880 } else if (Style.ColumnLimit == 0) { 881 NoColumnLimitFormatter Formatter(&Indenter); 882 Formatter.format(Indent, &TheLine); 883 } else { 884 UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style, 885 TheLine); 886 Formatter.format(Indent); 887 } 888 889 IndentForLevel[TheLine.Level] = LevelIndent; 890 PreviousLineWasTouched = true; 891 } else { 892 // Format the first token if necessary, and notify the WhitespaceManager 893 // about the unchanged whitespace. 894 for (const FormatToken *Tok = TheLine.First; Tok != NULL; 895 Tok = Tok->Next) { 896 if (Tok == TheLine.First && 897 (Tok->NewlinesBefore > 0 || Tok->IsFirst)) { 898 unsigned LevelIndent = Tok->OriginalColumn; 899 // Remove trailing whitespace of the previous line if it was 900 // touched. 901 if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine)) { 902 formatFirstToken(*Tok, PreviousLineLastToken, LevelIndent, 903 TheLine.InPPDirective); 904 } else { 905 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective); 906 } 907 908 if (static_cast<int>(LevelIndent) - Offset >= 0) 909 LevelIndent -= Offset; 910 if (Tok->isNot(tok::comment)) 911 IndentForLevel[TheLine.Level] = LevelIndent; 912 } else { 913 Whitespaces.addUntouchableToken(*Tok, TheLine.InPPDirective); 914 } 915 } 916 // If we did not reformat this unwrapped line, the column at the end of 917 // the last token is unchanged - thus, we can calculate the end of the 918 // last token. 919 PreviousLineWasTouched = false; 920 } 921 PreviousLineLastToken = TheLine.Last; 922 } 923 return Whitespaces.generateReplacements(); 924 } 925 926 private: 927 static bool inputUsesCRLF(StringRef Text) { 928 return Text.count('\r') * 2 > Text.count('\n'); 929 } 930 931 void deriveLocalStyle() { 932 unsigned CountBoundToVariable = 0; 933 unsigned CountBoundToType = 0; 934 bool HasCpp03IncompatibleFormat = false; 935 bool HasBinPackedFunction = false; 936 bool HasOnePerLineFunction = false; 937 for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { 938 if (!AnnotatedLines[i]->First->Next) 939 continue; 940 FormatToken *Tok = AnnotatedLines[i]->First->Next; 941 while (Tok->Next) { 942 if (Tok->Type == TT_PointerOrReference) { 943 bool SpacesBefore = 944 Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd(); 945 bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() != 946 Tok->Next->WhitespaceRange.getEnd(); 947 if (SpacesBefore && !SpacesAfter) 948 ++CountBoundToVariable; 949 else if (!SpacesBefore && SpacesAfter) 950 ++CountBoundToType; 951 } 952 953 if (Tok->Type == TT_TemplateCloser && 954 Tok->Previous->Type == TT_TemplateCloser && 955 Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) 956 HasCpp03IncompatibleFormat = true; 957 958 if (Tok->PackingKind == PPK_BinPacked) 959 HasBinPackedFunction = true; 960 if (Tok->PackingKind == PPK_OnePerLine) 961 HasOnePerLineFunction = true; 962 963 Tok = Tok->Next; 964 } 965 } 966 if (Style.DerivePointerBinding) { 967 if (CountBoundToType > CountBoundToVariable) 968 Style.PointerBindsToType = true; 969 else if (CountBoundToType < CountBoundToVariable) 970 Style.PointerBindsToType = false; 971 } 972 if (Style.Standard == FormatStyle::LS_Auto) { 973 Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11 974 : FormatStyle::LS_Cpp03; 975 } 976 BinPackInconclusiveFunctions = 977 HasBinPackedFunction || !HasOnePerLineFunction; 978 } 979 980 /// \brief Get the indent of \p Level from \p IndentForLevel. 981 /// 982 /// \p IndentForLevel must contain the indent for the level \c l 983 /// at \p IndentForLevel[l], or a value < 0 if the indent for 984 /// that level is unknown. 985 unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) { 986 if (IndentForLevel[Level] != -1) 987 return IndentForLevel[Level]; 988 if (Level == 0) 989 return 0; 990 return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; 991 } 992 993 /// \brief Get the offset of the line relatively to the level. 994 /// 995 /// For example, 'public:' labels in classes are offset by 1 or 2 996 /// characters to the left from their level. 997 int getIndentOffset(const FormatToken &RootToken) { 998 if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier()) 999 return Style.AccessModifierOffset; 1000 return 0; 1001 } 1002 1003 /// \brief Tries to merge lines into one. 1004 /// 1005 /// This will change \c Line and \c AnnotatedLine to contain the merged line, 1006 /// if possible; note that \c I will be incremented when lines are merged. 1007 void tryFitMultipleLinesInOne(unsigned Indent, 1008 SmallVectorImpl<AnnotatedLine *>::iterator &I, 1009 SmallVectorImpl<AnnotatedLine *>::iterator E) { 1010 // We can never merge stuff if there are trailing line comments. 1011 AnnotatedLine *TheLine = *I; 1012 if (TheLine->Last->Type == TT_LineComment) 1013 return; 1014 1015 if (Indent > Style.ColumnLimit) 1016 return; 1017 1018 unsigned Limit = Style.ColumnLimit - Indent; 1019 // If we already exceed the column limit, we set 'Limit' to 0. The different 1020 // tryMerge..() functions can then decide whether to still do merging. 1021 Limit = TheLine->Last->TotalLength > Limit 1022 ? 0 1023 : Limit - TheLine->Last->TotalLength; 1024 1025 if (I + 1 == E || (*(I + 1))->Type == LT_Invalid) 1026 return; 1027 1028 if (TheLine->Last->is(tok::l_brace)) { 1029 tryMergeSimpleBlock(I, E, Limit); 1030 } else if (Style.AllowShortIfStatementsOnASingleLine && 1031 TheLine->First->is(tok::kw_if)) { 1032 tryMergeSimpleControlStatement(I, E, Limit); 1033 } else if (Style.AllowShortLoopsOnASingleLine && 1034 TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) { 1035 tryMergeSimpleControlStatement(I, E, Limit); 1036 } else if (TheLine->InPPDirective && (TheLine->First->HasUnescapedNewline || 1037 TheLine->First->IsFirst)) { 1038 tryMergeSimplePPDirective(I, E, Limit); 1039 } 1040 } 1041 1042 void tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::iterator &I, 1043 SmallVectorImpl<AnnotatedLine *>::iterator E, 1044 unsigned Limit) { 1045 if (Limit == 0) 1046 return; 1047 AnnotatedLine &Line = **I; 1048 if (!(*(I + 1))->InPPDirective || (*(I + 1))->First->HasUnescapedNewline) 1049 return; 1050 if (I + 2 != E && (*(I + 2))->InPPDirective && 1051 !(*(I + 2))->First->HasUnescapedNewline) 1052 return; 1053 if (1 + (*(I + 1))->Last->TotalLength > Limit) 1054 return; 1055 join(Line, **(++I)); 1056 } 1057 1058 void 1059 tryMergeSimpleControlStatement(SmallVectorImpl<AnnotatedLine *>::iterator &I, 1060 SmallVectorImpl<AnnotatedLine *>::iterator E, 1061 unsigned Limit) { 1062 if (Limit == 0) 1063 return; 1064 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman && 1065 (*(I + 1))->First->is(tok::l_brace)) 1066 return; 1067 if ((*(I + 1))->InPPDirective != (*I)->InPPDirective || 1068 ((*(I + 1))->InPPDirective && (*(I + 1))->First->HasUnescapedNewline)) 1069 return; 1070 AnnotatedLine &Line = **I; 1071 if (Line.Last->isNot(tok::r_paren)) 1072 return; 1073 if (1 + (*(I + 1))->Last->TotalLength > Limit) 1074 return; 1075 if ((*(I + 1))->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, 1076 tok::kw_while) || 1077 (*(I + 1))->First->Type == TT_LineComment) 1078 return; 1079 // Only inline simple if's (no nested if or else). 1080 if (I + 2 != E && Line.First->is(tok::kw_if) && 1081 (*(I + 2))->First->is(tok::kw_else)) 1082 return; 1083 join(Line, **(++I)); 1084 } 1085 1086 void tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::iterator &I, 1087 SmallVectorImpl<AnnotatedLine *>::iterator E, 1088 unsigned Limit) { 1089 // No merging if the brace already is on the next line. 1090 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach) 1091 return; 1092 1093 // First, check that the current line allows merging. This is the case if 1094 // we're not in a control flow statement and the last token is an opening 1095 // brace. 1096 AnnotatedLine &Line = **I; 1097 if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace, 1098 tok::kw_else, tok::kw_try, tok::kw_catch, 1099 tok::kw_for, 1100 // This gets rid of all ObjC @ keywords and methods. 1101 tok::at, tok::minus, tok::plus)) 1102 return; 1103 1104 FormatToken *Tok = (*(I + 1))->First; 1105 if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore && 1106 (Tok->getNextNonComment() == NULL || 1107 Tok->getNextNonComment()->is(tok::semi))) { 1108 // We merge empty blocks even if the line exceeds the column limit. 1109 Tok->SpacesRequiredBefore = 0; 1110 Tok->CanBreakBefore = true; 1111 join(Line, **(I + 1)); 1112 I += 1; 1113 } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) { 1114 // Check that we still have three lines and they fit into the limit. 1115 if (I + 2 == E || (*(I + 2))->Type == LT_Invalid || 1116 !nextTwoLinesFitInto(I, Limit)) 1117 return; 1118 1119 // Second, check that the next line does not contain any braces - if it 1120 // does, readability declines when putting it into a single line. 1121 if ((*(I + 1))->Last->Type == TT_LineComment || Tok->MustBreakBefore) 1122 return; 1123 do { 1124 if (Tok->isOneOf(tok::l_brace, tok::r_brace)) 1125 return; 1126 Tok = Tok->Next; 1127 } while (Tok != NULL); 1128 1129 // Last, check that the third line contains a single closing brace. 1130 Tok = (*(I + 2))->First; 1131 if (Tok->getNextNonComment() != NULL || Tok->isNot(tok::r_brace) || 1132 Tok->MustBreakBefore) 1133 return; 1134 1135 join(Line, **(I + 1)); 1136 join(Line, **(I + 2)); 1137 I += 2; 1138 } 1139 } 1140 1141 bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::iterator I, 1142 unsigned Limit) { 1143 return 1 + (*(I + 1))->Last->TotalLength + 1 + 1144 (*(I + 2))->Last->TotalLength <= 1145 Limit; 1146 } 1147 1148 void join(AnnotatedLine &A, const AnnotatedLine &B) { 1149 assert(!A.Last->Next); 1150 assert(!B.First->Previous); 1151 A.Last->Next = B.First; 1152 B.First->Previous = A.Last; 1153 unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; 1154 for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { 1155 Tok->TotalLength += LengthA; 1156 A.Last = Tok; 1157 } 1158 } 1159 1160 bool touchesRanges(const CharSourceRange &Range) { 1161 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { 1162 if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), 1163 Ranges[i].getBegin()) && 1164 !SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(), 1165 Range.getBegin())) 1166 return true; 1167 } 1168 return false; 1169 } 1170 1171 bool touchesLine(const AnnotatedLine &TheLine) { 1172 const FormatToken *First = TheLine.First; 1173 const FormatToken *Last = TheLine.Last; 1174 CharSourceRange LineRange = CharSourceRange::getCharRange( 1175 First->WhitespaceRange.getBegin().getLocWithOffset( 1176 First->LastNewlineOffset), 1177 Last->getStartOfNonWhitespace().getLocWithOffset( 1178 Last->TokenText.size() - 1)); 1179 return touchesRanges(LineRange); 1180 } 1181 1182 bool touchesPPDirective(SmallVectorImpl<AnnotatedLine *>::iterator I, 1183 SmallVectorImpl<AnnotatedLine *>::iterator E) { 1184 for (; I != E; ++I) { 1185 if ((*I)->First->HasUnescapedNewline) 1186 return false; 1187 if (touchesLine(**I)) 1188 return true; 1189 } 1190 return false; 1191 } 1192 1193 bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) { 1194 const FormatToken *First = TheLine.First; 1195 CharSourceRange LineRange = CharSourceRange::getCharRange( 1196 First->WhitespaceRange.getBegin(), 1197 First->WhitespaceRange.getBegin().getLocWithOffset( 1198 First->LastNewlineOffset)); 1199 return touchesRanges(LineRange); 1200 } 1201 1202 virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) { 1203 AnnotatedLines.push_back(new AnnotatedLine(TheLine)); 1204 } 1205 1206 /// \brief Add a new line and the required indent before the first Token 1207 /// of the \c UnwrappedLine if there was no structural parsing error. 1208 /// Returns the indent level of the \c UnwrappedLine. 1209 void formatFirstToken(const FormatToken &RootToken, 1210 const FormatToken *PreviousToken, unsigned Indent, 1211 bool InPPDirective) { 1212 unsigned Newlines = 1213 std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1); 1214 // Remove empty lines before "}" where applicable. 1215 if (RootToken.is(tok::r_brace) && 1216 (!RootToken.Next || 1217 (RootToken.Next->is(tok::semi) && !RootToken.Next->Next))) 1218 Newlines = std::min(Newlines, 1u); 1219 if (Newlines == 0 && !RootToken.IsFirst) 1220 Newlines = 1; 1221 1222 // Insert extra new line before access specifiers. 1223 if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) && 1224 RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1) 1225 ++Newlines; 1226 1227 Whitespaces.replaceWhitespace( 1228 RootToken, Newlines, Indent, Indent, 1229 InPPDirective && !RootToken.HasUnescapedNewline); 1230 } 1231 1232 unsigned getColumnLimit(bool InPPDirective) const { 1233 // In preprocessor directives reserve two chars for trailing " \" 1234 return Style.ColumnLimit - (InPPDirective ? 2 : 0); 1235 } 1236 1237 FormatStyle Style; 1238 Lexer &Lex; 1239 SourceManager &SourceMgr; 1240 WhitespaceManager Whitespaces; 1241 std::vector<CharSourceRange> Ranges; 1242 SmallVector<AnnotatedLine *, 16> AnnotatedLines; 1243 1244 encoding::Encoding Encoding; 1245 bool BinPackInconclusiveFunctions; 1246 }; 1247 1248 } // end anonymous namespace 1249 1250 tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex, 1251 SourceManager &SourceMgr, 1252 std::vector<CharSourceRange> Ranges) { 1253 Formatter formatter(Style, Lex, SourceMgr, Ranges); 1254 return formatter.format(); 1255 } 1256 1257 tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, 1258 std::vector<tooling::Range> Ranges, 1259 StringRef FileName) { 1260 FileManager Files((FileSystemOptions())); 1261 DiagnosticsEngine Diagnostics( 1262 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), 1263 new DiagnosticOptions); 1264 SourceManager SourceMgr(Diagnostics, Files); 1265 llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName); 1266 const clang::FileEntry *Entry = 1267 Files.getVirtualFile(FileName, Buf->getBufferSize(), 0); 1268 SourceMgr.overrideFileContents(Entry, Buf); 1269 FileID ID = 1270 SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User); 1271 Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr, 1272 getFormattingLangOpts(Style.Standard)); 1273 SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID); 1274 std::vector<CharSourceRange> CharRanges; 1275 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) { 1276 SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset()); 1277 SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength()); 1278 CharRanges.push_back(CharSourceRange::getCharRange(Start, End)); 1279 } 1280 return reformat(Style, Lex, SourceMgr, CharRanges); 1281 } 1282 1283 LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) { 1284 LangOptions LangOpts; 1285 LangOpts.CPlusPlus = 1; 1286 LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1; 1287 LangOpts.LineComment = 1; 1288 LangOpts.Bool = 1; 1289 LangOpts.ObjC1 = 1; 1290 LangOpts.ObjC2 = 1; 1291 return LangOpts; 1292 } 1293 1294 } // namespace format 1295 } // namespace clang 1296